我有一个代码段看起来像这样:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
pid_t first, last;
last = fork();
if (last == 0) {
char *args[] = { "./last", NULL };
char *env[] = { NULL };
execve("./last", args, env);
_exit(1);
} else if (last == -1) {
fprintf(stderr, "Error: failed to fork last.\n");
exit(1);
}
first = fork();
if (first == -1) {
fprintf(stderr, "Error: failed to fork first.\n");
exit(1);
} else if (first > 0) {
int status;
waitpid(first, &status, 0);
} else {
char *args[] = { "./first", NULL };
char *env[] = { NULL };
execve("./first", args, env);
_exit(1);
}
return 0;
}
从某种意义上说,这可以正常工作,我可以看到进程正在被调用并正在运行。但是,我的问题是该进程last
具有无限循环,并且当进程first
终止时,它仍然保持运行状态。C中是否有一种方法可以迫使进程last
在此过程first
完成时也终止?
kill()
应该很有趣。从手册页kill()
:
#include <sys/types.h>
#include <signal.h>
int kill(pid_t pid, int sig);
由于fork()
在父级中返回子级PID,因此您可以使用来调用kill()
。这是修改后的代码和测试运行。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h> // Modification 1
int main(int argc, char *argv[]) {
pid_t first, last;
last = fork();
if (last == 0) {
char *args[] = { "./last", NULL };
char *env[] = { NULL };
execve("./last", args, env);
_exit(1);
} else if (last == -1) {
fprintf(stderr, "Error: failed to fork last.\n");
exit(1);
}
first = fork();
if (first == -1) {
fprintf(stderr, "Error: failed to fork first.\n");
exit(1);
} else if (first > 0) {
int status;
waitpid(first, &status, 0);
kill(last, SIGINT); // Modification 2
} else {
char *args[] = { "./first", NULL };
char *env[] = { NULL };
execve("./first", args, env);
_exit(1);
}
return 0;
}
终端会议(之前):
$ ls test first last
first last test
$ ./test
$ ps aux | grep last
root 165130 0.0 0.0 2136 752 pts/3 S 16:58 0:00 ./last
root 165135 0.0 0.0 6136 892 pts/3 S+ 16:58 0:00 grep last
终端会议(之后):
$ ls test first last
first last test
$ ./test
$ ps aux | grep last
root 165240 0.0 0.0 6136 836 pts/3 S+ 17:01 0:00 grep last
关于要传递的信号:默认动作是终止的任何人。您可以从signal
手册页中找到更多信息。由于我不知道last
可执行文件中到底有什么内容,因此我假设没有注册信号处理程序SIGINT
,因此在last
gets时SIGINT
,程序默认终止。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句