【发布时间】:2012-04-01 23:49:34
【问题描述】:
我有这样的情况:
start();
<Some code>
end();
我希望start() 函数启动一个异步执行某些操作的进程(而不是单独的线程)(我的意思是在生成进程后立即,控件应该返回父进程并且生成的进程进入“后台”)父进程,然后在<Some code> 块完成后,end() 函数将kill 与start() 关联的进程ID。
我不知道该怎么做,尤其是使父子代码块异步的部分;需要一些帮助。谢谢。
编辑:在得到成员的帮助后,我能够编写这段代码,但这有问题,如果有人能指出错误,那就太好了。我想要_do_() 只是启动一个子进程,如果_stop_() 无法杀死它,它就永远不会结束。但是由于某种原因,父进程迷路了,程序在while()循环上无限期地运行。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
pid_t id = 0;
int _do_()
{
//int status;
pid_t childpid; /* variable to store the child's pid */
FILE *fp= NULL;
childpid = fork();
//child stuff
if (childpid == 0)
{
id = getpid();
fp = fopen ("Log.txt", "w+");
while (1)
{
fprintf(fp, "Logging info...\n");
fflush(fp);
}
fclose(fp);
}
if (childpid < 0) /* fork returns -1 on failure */
{
perror("fork"); /* display error message */
exit(-1);
}
return 0;
}
//kill child process in _do_()
int _stop_()
{
int en;
printf("Going to kill child ID: %d\n", id);
if (kill ( id , SIGKILL ) < 0)
{
en = errno;
printf("Error while trying to KILL process: %s\n", strerror(en));
}
printf("Logging ended\n");
return 0;
}
int main(int argc, char* argv[])
{
int i;
_do_();
for (i = 0; i < 200; i++)
;
_stop_();
printf("\nEnded...\n");
return 0;
}
EDIT2:我不能做我想做的事,从end() 杀死一个从start() 开始的进程,而是启动一个守护进程并让它转储文件上的值,直到文件大小达到某个预先指定的限制.这是最接近我想要的。
【问题讨论】:
-
见this SO question - 它包括实现
start的代码,它要求end的代码。 -
请在答案中查看我的第二次编辑,我提到了为什么你的 kill 没有杀死进程。