如问题所示,我正在subprocess.open module
C
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, preexec_fn=os.setsid)
print p.pid
我正在尝试生成一个进程,然后获取进程ID。
`cmd` is a c program that is spawned
在C中,我相信getpid()
可以胜任。
但是在我产生这个过程之后,我不知道如何告诉getpid()
获得那个衍生过程,pid。
void run_apps(pid) {
printf("process ID is %d\n", (int) getpid());
}
这显然是给出了当前的进程ID。
答案 0 :(得分:1)
在C中,通过首先调用fork()
来创建一个新进程(最终的子进程),然后执行子进程的exec*()
函数系列之一,获得最大数量的选项。原始进程和新进程将同时运行,因此您可以通过管道或套接字对交换(读取和/或写入数据)。最后,使用例如waitpid()
在一个循环中等待新进程退出,并“收获”其退出状态。例如:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
int main(void)
{
pid_t child, p;
int status;
/*
* Prepare pipes et cetera first.
*/
/* Fork to create the subprocess. */
child = fork();
if (child == (pid_t)-1) {
/* Cannot fork(); usually out of resources (user limits).
* see errno for details. With <string.h>, you can use
* strerror(errno) to obtain the error string itself. */
return 1;
} else
if (!child) {
/* This is the child process itself.
* Do whatever cleanup is necessary, then
* execute the subprocess command. */
execlp("/bin/ls", "ls", "-lA", NULL);
/* This is only reached if the exec failed;
* again, see errno for reason.
* Always have the child process exit! */
return 127;
}
/* This is only run by the parent process
* (because the child always exits within the
* else if body above).
*
* The subprocess PID is 'child'.
*/
/* Wait for the child process to exit. */
do {
status = 0;
p = waitpid(child, &status, 0);
if (p == (pid_t)-1 && errno != EINTR)
break; /* Error */
} while (p != child);
if (p != child) {
/* Child process was lost.
* If (p == (pid_t)-1), errno describes the error.
*/
} else
if (WIFEXITED(status)) {
/* Child process exited with WEXITSTATUS(status) status.
* A status of 0 (or EXIT_SUCCESS) means success,
* no errors occurred. Nonzero usually means an error,
* but codes vary from binary to binary.
*/
} else
if (WIFSIGNALED(status)) {
/* Child process died from WTERMSIG(status) signal.
* If you include <string.h>, you can use
* strsignal(WTERMSIG(status))
* to obtain the name (string) of the terminating signal.
*/
} else {
/* Child process died from unknown causes.
*/
}
/* All done. */
return 0;
}
就个人而言,我更喜欢使用socketpair()
在我控制的进程之间创建Unix域流或数据报套接字,如果子进程只是一些随机二进制文件,则通过pipe()
创建管道。在所有情况下,您都可以使用{{3}替换标准输入(STDIN_FILENO
描述符),标准输出(STDOUT_FILENO
描述符)和标准错误(STDERR_FILENO
描述符)和套接字或管道。功能。您甚至可以从父级访问/proc/[child]/
下的伪文件,以便在需要时观察子进程的状态。
取决于您需要如何与子进程通信 - 从/向文件输入/输出?记忆中的字符串?为输出动态分配缓冲区 - 有很多变种。当需要精确控制和/或全双工(读写和写入)和/或异步通信时,通常使用与上面类似的代码。
您可以在自己喜欢的搜索引擎中搜索dup2()
,以获取不同质量的示例。
如果您想要一个更简单的解决方案,并且您只需捕获命令的输出(不向命令提供输入,或者可能从文件提供输入),您可以使用
的某些变体#include <unistd.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
FILE *sub;
pid_t subpid;
int status;
sub = popen("setsid /bin/sh -c 'echo $$ ; exec command args' </dev/null", "rb");
if (!sub) {
/* popen() failed. */
return 1;
}
/* Read the first line from sub. It contains the PID for the command. */
{
char buffer[32], *line, dummy;
int value;
line = fgets(buffer, sizeof buffer, sub);
if (!line) {
/* setsid failed, or non-POSIXy system (Windows?) */
pclose(sub);
return 1;
}
if (sscanf(line, "%d%c", &value, &dummy) != 1 || value < 2) {
/* Internal bug, or extra output? */
pclose(sub);
return 1;
}
/* subpid is also the session ID and the process group ID,
* because it is the session leader. */
subpid = value;
}
/* Read from sub using standard I/O, to capture command output. */
/* After no more output to read from sub, reap the subprocess. */
errno = 0;
do {
status = pclose(sub);
} while (status == -1 && errno == EINTR);
if (status) {
/* Problem: sub exited with nonzero exit status 'status',
* or if status == -1, some other error occurred. */
} else {
/* Sub exited with success (zero exit status). */
}
/* Done. */
return 0;
}
在Linux中,popen()
使用/bin/sh
shell(根据POSIX.1规范),我们可以使用setsid
命令行实用程序来创建新会话。在命令中,echo $$
是sh
命令,它输出shell PID,exec CMD...
用命令替换shell;因此,即使在执行命令之前,我们也会得到命令的PID。