gpt4 book ai didi

c - 如何在另一个子进程完成时终止子进程?

转载 作者:行者123 更新时间:2023-12-03 09:53:46 26 4
gpt4 key购买 nike

我有一个看起来像这样的代码段:

#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 中是否有一种方法可以在进程 first 完成时强制此处的进程 last 也终止?

最佳答案

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;
}

终端 session (之前):

$ 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

终端 session (之后):

$ 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得到SIGINT,程序默认终止。

关于c - 如何在另一个子进程完成时终止子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62533200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com