如何在C程序中启动另一个进程?

时间:2022-06-17 19:46:31
如何在C程序中启动另一个进程?该进程启动后期望是一个独立的进程,当前进程不需要管理也不需要关心这个进程。
实际上,我是期望在一个程序中启动另一个程序,启动后,两者成为互不相关的程序。

7 个解决方案

#1


system或者exec函數可不可以?

#2


system, popen, fork+exec

#3


就用system或者exec族的函数调用一下吧

#4


先fork,然后再用exec调用下就好了。个人感觉是这样,具体你可以试试

#5


system调用时,把被调用进程放入后台执行
或者自己fork exec,然后把子进程放入一个单独的会话

#6


#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<sys/types.h>

int main()
{
pid_t childpid;
int status;
if((childpid=fork())==-1) //fork( )命令
{
perror("fork:");
}
else if(childpid==0) // This is child process!
{
char *args[]={"/home/sk/code/GNU/pripds",NULL};
puts("in child:\n");
if(execve("pripds",args,NULL)==-1) // pripds 是我自己的一个程序。。
{
perror("execve:");
}
exit(EXIT_SUCCESS);
}
else //This is  parent process! 
{
waitpid(childpid,&status,0);  //这里也可以用非阻塞wait,这样两个进程就不会相干扰了
puts("in parent:\n");
printf("\tparent pid=%d\n",getpid());
}
}


看看是否有用。。^^

#7


引用 3 楼 louyong0571 的回复:
就用system或者exec族的函数调用一下吧


嗯,需要注意的是system()是需要返回结果的,也就是父进程会一直阻塞,直到子进程结束。
当然,可以在system()参数的最后,加个&,以让子进程后台运行。

#1


system或者exec函數可不可以?

#2


system, popen, fork+exec

#3


就用system或者exec族的函数调用一下吧

#4


先fork,然后再用exec调用下就好了。个人感觉是这样,具体你可以试试

#5


system调用时,把被调用进程放入后台执行
或者自己fork exec,然后把子进程放入一个单独的会话

#6


#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<sys/types.h>

int main()
{
pid_t childpid;
int status;
if((childpid=fork())==-1) //fork( )命令
{
perror("fork:");
}
else if(childpid==0) // This is child process!
{
char *args[]={"/home/sk/code/GNU/pripds",NULL};
puts("in child:\n");
if(execve("pripds",args,NULL)==-1) // pripds 是我自己的一个程序。。
{
perror("execve:");
}
exit(EXIT_SUCCESS);
}
else //This is  parent process! 
{
waitpid(childpid,&status,0);  //这里也可以用非阻塞wait,这样两个进程就不会相干扰了
puts("in parent:\n");
printf("\tparent pid=%d\n",getpid());
}
}


看看是否有用。。^^

#7


引用 3 楼 louyong0571 的回复:
就用system或者exec族的函数调用一下吧


嗯,需要注意的是system()是需要返回结果的,也就是父进程会一直阻塞,直到子进程结束。
当然,可以在system()参数的最后,加个&,以让子进程后台运行。