我需要实现一个将执行文件并发送执行结果的子进程,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!rn");
exit(0);
}
else{
int status;
alarm(10);
waitpid(-1,&status,0);
printf("status %d _n);
}
如何使子过程中断?
谢谢
首先,您需要将孩子pid实际存储到child_pid中。它已从叉子返回以进行父进程,因此将您的叉子调用更改为
child_pid = fork();
if(child_pid == 0)
{
...
否则,您的杀戮电话将通过随机值。幸运的是,它似乎违约为0,这意味着在同一过程组中杀死所有过程,因此您的孩子过程被杀死。
其次,而不是调用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))
{
....
}
}
}
这样,您只有一个孩子的过程正在运行您的可执行文件,并且您的何时以及如何退出。