Linux的进程操作

获取ID
#include <stdio.h>
#include <unintd.h>
#inlcude <stdlib.h>
pid_t getpid(void)//获取本进程的ID
//printf("PID=%d\n",getpid());
pid_t getppid(void)//获取父进程
//printf("PID=%d\n",getppid());

进程的创建--fork
//fork:子进程和父进程拷贝数据段
pid_t fork(void);
//fork在于它被调用一次,则是有返回两次,并且有三种不同的返回值
//在父进程中,fork返回的是子进程的ID号
//在子进程中,fork返回的是零
//如果出错,则是会返回负值
//#include <stdio.h>
//#include <stdlib.h>
//int main(void)
{
//pid_t pid;
//int count=0;
//pid=fork();
//count++;
printf("count=%d\n",count);
}
输出的结果:count =1
                   count=1
分析:有两次结果输出,是因为fork创建子进程是,父进程先执行;接着子进程执行都有返回值;第一次和第二次结果都是1的原因:父进程在执行完之后,输出的结果是1;对子进程来说,fork出来之后,和父进程之间可以进行代码的拷贝,而不是数据,所有在子进程执行count++时,它的初值是0的。
-----------------------------------------------------------------------------------
创建进程--vfork
//子进程和父进程共享数据段
//#include <stdio.h>
//#include <stdlib.h>
//int main(void)
{
//pid_t pid;
//int count=0;
//pid=fork();
//count++;
printf("count=%d\n",count);
}
输出:count =1//子进程先执行
              count=2//父进程执行
--------------------------------------------------------
exec函数族
//exec用于被执行的程序替换调用它的程序
int execl(const char *path,const char argn1,...)
//path 含完成的目录路径
//arg1---argn代表的是被执行程序所需要的参数,含函数名,最后需要以NULL结束
//execl("/bin/ls","ls","-al","/etc/password",(char*)0);
-----------------------------------------------------------
int execp(const char *path,const char arg1...)
//path:被执行程序的目录,不需要包含完整的路径
execp("ls","ls","-al","/etc/password",(char*)0);
//第一个“ls”代表的是执行程序的名字,第二个"ls"表示的是指令
---------------------------------------------------------------------
int execv(const char *path,const char argv[])
//path 含完成的目录路径
--------------------------------------------
进程的等待
//#include <stdio.h>
//#inlcude <sys/wait.h>
//#inlcude<sys/types.h>
//pid_t wait(int *status)
例子:
#int main
{
    pid_t pc,pr;
    pc=fork();
    if(pc==0)//如果是子进程
    {
         printf("child fork %d!\n",getpid());
         sleep(10);
     }
    else if (pc>0)//如果是父进程
    {
         pr=wait(NULL);
         printf("i catch a child process with pid of %d\n",pr);
     }
}
输出结果:child fork..
                        i catch a child process with...

猜你喜欢

转载自blog.csdn.net/XJH0918/article/details/48543929