私の質問はこれと同じように聞こえますが、そうではありません:
C を使用して Linux でバックグラウンドでプロセスを開始する
fork() の実行方法は知っていますが、プロセスをバックグラウンドに送信する方法は知りません。私のプログラムは、パイプとバックグラウンド プロセスをサポートする単純なコマンド UNIX シェルのように動作するはずです。&
パイプとフォークを実行できましたが、プログラムの最後の行のようにプロセスをバックグラウンドに送信する方法がわかりません。
~>./a.out uname
SunOS
^C
my:~>./a.out uname &
バックグラウンドプロセスを達成する方法は?
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#define TIMEOUT (20)
int main(int argc, char *argv[])
{
pid_t pid;
if(argc > 1 && strncmp(argv[1], "-help", strlen(argv[1])) == 0)
{
fprintf(stderr, "Usage: Prog [CommandLineArgs]\n\nRunSafe takes as arguments:\nthe program to be run (Prog) and its command line arguments (CommandLineArgs) (if any)\n\nRunSafe will execute Prog with its command line arguments and\nterminate it and any remaining childprocesses after %d seconds\n", TIMEOUT);
exit(0);
}
if((pid = fork()) == 0) /* Fork off child */
{
execvp(argv[1], argv+1);
fprintf(stderr,"Failed to execute: %s\n",argv[1]);
perror("Reason");
kill(getppid(),SIGKILL); /* kill waiting parent */
exit(errno); /* execvp failed, no child - exit immediately */
}
else if(pid != -1)
{
sleep(TIMEOUT);
if(kill(0,0) == 0) /* are there processes left? */
{
fprintf(stderr,"\Attempting to kill remaining (child) processes\n");
kill(0, SIGKILL); /* send SIGKILL to all child processes */
}
}
else
{
fprintf(stderr,"Failed to fork off child process\n");
perror("Reason");
}
}
平易な英語での解決策はここにあるようです: How do I exec() a process in the background in C?
SIGCHLD をキャッチし、ハンドラーで wait() を呼び出します。
私は正しい軌道に乗っていますか?