0

i want to make a child process run in background using fork and execvp, i saw many same questions but for some reason none of them really ment run in background. when i mean i want the program to run in background i mean i dont want to see it at all. currently i have a program called e_print whuch prints output every 1 second, i want to keep it running but not see the output (really run in background) here my code:

        if((son = fork())==0){//son process
        i = execvp(tokens_set[0],tokens_set);//tokens set was previously set
        if(i == (-1)){
            perror("couldn't find the command: ");
        }
        exit(0);

    }else{ // father process
        printf("father proccess goes on\n");
    }

for some reason all the guides and questions i saw called it run in background but the childs output was seen.

i want to keep the father running, say ask for another input from user and meanwhile i want the e_print process to run. same as:

./e_print &

from terminal.

4

3 回答 3

0

它与实际的 fork 或 execvp 调用没有任何关系,它与您如何等待它们有关。

对于像我假设你到目前为止一直在处理的前台进程,你将分叉新进程,使用 exec 运行程序,然后使用 wait() 或 waitpid() 在父进程中等待子进程。如果一个进程是前台或后台只取决于你在哪里以及如何等待孩子。您还可以安装一个信号处理程序来与孩子们交流

于 2013-12-10T16:22:28.860 回答
0

如果您唯一关心的是输出,那么您要做的就是关闭并将子程序的标准输出重新打开到 /dev/null。

在调用 execvp 之前的“儿子”进程中,执行以下操作:

close(0);
close(1);
close(2);
open("/dev/null", O_RDONLY);
open("/dev/null", O_WRONLY);
open("/dev/null", O_WRONLY);

当然,在实际程序中,您应该始终检查返回码。

于 2013-12-10T16:31:39.420 回答
0

您可以尝试守护子进程。不确定这是否真的是你想要的。

于 2013-11-07T19:59:42.890 回答