当前位置: 技术问答>linux和unix
关于system()函数问题!
来源: 互联网 发布时间:2015-07-15
本文导语: system("your")函数调用之后会创建一个子进程,而父进程自己怎么被停止了呀?搞不懂,我希望不但能创建一个新的进程,而且原进程仍然处于活动状态,请问怎么办呀? | 父进程不是被停止了, 而是bl...
system("your")函数调用之后会创建一个子进程,而父进程自己怎么被停止了呀?搞不懂,我希望不但能创建一个新的进程,而且原进程仍然处于活动状态,请问怎么办呀?
|
父进程不是被停止了, 而是block并且不可被中断了。
system() executes a command specified in string by calling /bin/sh -c string, and
returns after the command has been completed. During execution of the command,
SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.
BUGS
It is extremely unfortunate that the libc version of system() ignores interrupts.
This makes programs that call it from a loop uninterruptable. This means that for
such purposes one should not use system() but a private version like (warning:
untested code!)
int my_system (const char *command) {
int pid, status;
if (command == 0)
return 1;
pid = fork();
if (pid == -1)
return -1;
if (pid == 0) {
char *argv[4];
argv[0] = "sh";
argv[1] = "-c";
argv[2] = command;
argv[3] = 0;
execve("/bin/sh", argv, environ);
exit(127);
}
do {
if (waitpid(pid, &status, 0) == -1) {
if (errno != EINTR)
return -1;
} else
return status;
} while(1);
}
system() executes a command specified in string by calling /bin/sh -c string, and
returns after the command has been completed. During execution of the command,
SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.
BUGS
It is extremely unfortunate that the libc version of system() ignores interrupts.
This makes programs that call it from a loop uninterruptable. This means that for
such purposes one should not use system() but a private version like (warning:
untested code!)
int my_system (const char *command) {
int pid, status;
if (command == 0)
return 1;
pid = fork();
if (pid == -1)
return -1;
if (pid == 0) {
char *argv[4];
argv[0] = "sh";
argv[1] = "-c";
argv[2] = command;
argv[3] = 0;
execve("/bin/sh", argv, environ);
exit(127);
}
do {
if (waitpid(pid, &status, 0) == -1) {
if (errno != EINTR)
return -1;
} else
return status;
} while(1);
}
|
system("your") =
1)先fork,再忽略SIGINT和SIGQUIT,以及阻塞SIGCHLD
2)后exec("/bin/sh -c your");
3)然后主进程:wait(..) // 等待2)结束。
如果想具体了解,可以看看apue(unix环境高级编程)英文版, page 314, 给了一个自己实现的system()函数。
1)先fork,再忽略SIGINT和SIGQUIT,以及阻塞SIGCHLD
2)后exec("/bin/sh -c your");
3)然后主进程:wait(..) // 等待2)结束。
如果想具体了解,可以看看apue(unix环境高级编程)英文版, page 314, 给了一个自己实现的system()函数。
|
不会吧,那就fork之后再system("your").
|
其实system就等同于sh
那你如果想执行命令的话,可以用exec函数来执行,可以保证进程还是原进程
那你如果想执行命令的话,可以用exec函数来执行,可以保证进程还是原进程
|
牛人好多阿!!!
|
关注 :)