中断调用函数 popen 的进程

Interrupt a process calling the function popen

我需要实现一个子进程来执行文件并发送执行结果,2 进程将与共享内存段通信。

我的问题是我想在 10 秒后终止调用 popen 的子进程,但函数 popen 忽略了信号。

这是我的代码(不包括共享内存段):

void kill_child(int sig)
{
 kill(child_pid,SIGKILL);
printf("processus killed \n");

}

/*code....*/

signal(SIGALRM,(void (*)(int))kill_child);

if(fork()==0){
                res.buffer=true;
                FILE * fd;
                char cmd[BUFFER_SIZE],output[BUFFER_SIZE];
                strcpy(cmd,"./");
                strcat(cmd,res.filepath);
                system(cmd);
                if((fd=popen(cmd,"r"))== NULL)
                    exit(1);
                else 
                    res.status=200;


                strcpy(output,"");
                while(fgets(buf,sizeof(buf)-1,fd))
                    strcat(output,buf);

                if(pclose(fd))
                    exit(1);

                strcat(res.customHTML,output);
                res.buffer=true;


                int err = sendResponse(res,args->client_fd);
                if (err < 0) on_error("failed!\r\n");



                exit(0);


 } 

 else{

               int status;
               alarm(10);
               waitpid(-1,&status,0);
               printf("status %d _n);
}

如何让子进程可中断?

感谢

首先,您需要将子 PID 实际存储到 child_pid。它是从父进程的 fork 返回的,因此将 fork 调用更改为

child_pid = fork();
if(child_pid == 0)
  {
...

否则您的 kill 调用将传递一个随机值。幸运的是,它似乎默认为 0,kill 意味着杀死同一进程组中的所有进程,因此您的子进程被杀死。

其次,而不是调用 popen() 自己调用可执行文件(例如)execvp() 并让父级使用您自己创建的管道读取输出...

int fds[2];

pipe(fds);
child_pid = fork();
if(child_pid == 0)
  {
  char *cmd[]={"mycmd",NULL};

  /* Replace stdout with the output of the pipe and close the original */
  dup2(fds[1],1);
  close(fds[0]);
  close(fds[1]);
  execvp(cmd[0],cmd);
  }
else
  {
  close(fds[1]);
  alarm(10);
  while(...)
     {
     read(fds[0],....);
     if(waitpid(child_pid,&status,WNOHANG))
         {
         ....
         }
     }
  }

这样您只有一个子进程,即 运行 您的可执行文件,并且您可以看到它何时以及如何退出。