C - 我如何 运行 在后台使用 exec 的程序?

C - How do I run a program in the background using exec?

有一个程序我可以在终端上 运行 像这样:./program &

但我正在尝试使用 execvp 执行此操作,但它不起作用:

            pid = fork();
            char *argv[3] = {"./program", "&",  NULL};

            if ( pid == 0 ) {
                execvp( argv[0], argv );
            }
            else{
                wait(NULL);
            }

我这里做错了什么?

您在 argv 数组中的 "&" 不会执行您想要的操作,并且可能是此处问题的根源。那是程序参数的地方,& 是一个 shell 命令,而不是程序参数。删除它,因为 ./program 无论如何都会 运行 在一个单独的进程中,因为你已经分叉了。

, the ending & is a shell syntax (it is technically not a shell command) related to job control.

在你的问题中,不清楚你为什么需要它。您可以不使用那个 "&",您的代码应该可以工作。另请阅读 background processes, about terminal emulators, about process groups. Read the tty demystified.

顺便说一句,您可以使用 waitpid(2) and specify the pid. You generally need some waiting (e.g. wait, waitpid, wait4(2), etc ....) to avoid having zombie processes. You may want to handle the SIGCHLD signal, but read signal(7) & signal-safety(7).

而不是 wait

也许您想使用 daemon(3) function. See also setsid(2), setpgrp(2), and credentials(7). Otherwise, you probably should call wait much later in your program. You might want to redirect (using dup2(2)), perhaps to /dev/null, to some other open(2)-ed file descriptor, to some pipe(7), etc..., the stdin (and/or stdout and stderr) of your child process. You may also want to multiplex input or output using poll(2)

您的代码应该 handle the failure of fork(2) (when it gives -1), perhaps using perror(3) in such case. You also should handle failure of execvp(3).

在某些有限和特定的特定情况下,您可能需要 popen(3) a sh, nohup(1)batchatbash,但通常不需要。

(不了解您的动机,以及为什么要 运行 background 中的某些内容,我们无法为您提供更多帮助)