我有這樣的情況:即做一些事情異步啓動在* nix中採用C異步進程
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:我不能做什麼,我想,殺的過程開始於start()
從end()
,而是推出了一個守護進程,讓它在文件上,直到達到某個預先指定的限制文件大小傾倒值。這是最接近我想要的。
什麼操作系統? – 2012-04-01 23:54:00
請參閱[這個SO問題](http://stackoverflow.com/q/7794273/960195) - 它包含實現'start'的代碼,它要求'end'的代碼。 – 2012-04-01 23:57:02
Linux系統... – Sayan 2012-04-01 23:57:57