进程产生方式

基本示例

#include <sys/types.h>
#include <stdio.h>
#include<unistd.h>
int main()
{
        pid_t pid;
        pid=fork();
        if(pid==-1)
        {
                printf("Error");
                return -1;
        }
        else if(pid==0)
        {
                printf("child:%d,%d,%d\n",pid,getpid(),getppid());

        }
        else
        {
                printf("parent:%d,%d,%d\n",pid,getpid(),getppid());
        }
        return 0;
}

执行结果

[dong@localhost test]# gcc -o a pid.c
[dong@localhost test]# ./a
parent:5865,5864,5615
child:0,5865,1

Fork出来子进程的父进程ID号为fork函数的ID号

 

system方式

#include <sys/types.h>
#include <stdio.h>
#include<unistd.h>
int main()
{
        int ret;
        printf("%d\n",getpid());
        ret=system("ps");
        printf("return:%d\n",ret);
        return 0;
}

运行结果

[dong@localhost test]# gcc -o a pid.c
[dong@localhost test]# ./a
3115
  PID TTY          TIME CMD
 2959 pts/0    00:00:00 su
 2967 pts/0    00:00:00 csh
 3115 pts/0    00:00:00 a
 3116 pts/0    00:00:00 ps
return:0

  执行fork函数和system函数系统都会建立一个新的进程,执行调用者操作,而原来的进程还会存在

 

exec 函数用新的进程替代原有进程

#include <sys/types.h>
#include <stdio.h>
#include<unistd.h>
int main()
{
         char *args[]={"/bin/ls",NULL};
         printf("pid:%d\n",getpid());
        if(execve("/bin/ls",args,NULL)<0)
        {
                printf("Create error\n");
        }
        return 0;
}

 执行结果 

[dong@localhost test]# gcc -o a pid.c
[dong@localhost test]# ./a
pid:10646
a	 backup  data.sh   for.sh  mm	   pid.c   read.sh  ss	      test
back.sh  bash	 data.txt  main.c  ope.sh  pid.c~  sh	    string.c

  

 

posted @ 2014-01-12 23:27  bradleydan  阅读(176)  评论(0)    收藏  举报