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

标签 c linux fork exec

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

#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/

相关文章:

iphone - 我必须制作一个与支持 Modbus 协议(protocol)的设备进行通信的 iPhone 应用程序

c - gcc 将忙等待优化为死循环

python - subprocess.check_output 与 subprocess.call 的性能

python - 在前台生成一个子进程,即使在 python 退出之后

c - 如何创建一个使用输入 GTK 更改文本的窗口

c - 如何在应用程序运行时在 Windows 中使用 MSDN 函数记录时区更改

linux - 使用带有 gnome-keyring 的 Git 凭证助手作为 Sudo 时出错

linux - lpr 打印具有不同名称和目录的文件

c - GTK+ gtk_widget_show_all() 在 fork 和 exec() 之后需要很长时间

c - fork 进程的子进程中的标准输入/输出/错误重定向