Linux进程

来源:互联网 发布:什么测试网络掉包 编辑:程序博客网 时间:2024/05/01 02:29

相关函数:

1.pid_t  getpid(void)

功能:获取当前进程的ID;


2.pid_t  getppid(void)

功能:获取当前进程的父进程的ID;


3.pid_t  fork(void)

返回值:

-1     创建进程失败;并且记录到errno;

0       子进程的返回值

子进程的ID     父进程得到子进程作为返回值;

说明:fork是完全copy了一份父进程的地址空间给子进程,让彼此可以独立的执行。

父子进程执行的先后顺序不定,子进程有自己的pid;

举例:

#include<stdio.h>#include<unistd.h>int main(){    fork();    fork();    fork();    printf("process is %d\n",getpid());    return 0;}
执行结果:
[root@localhost ~]# ./forkcountprocess is 3470[root@localhost ~]# process is 3473process is 3472process is 3471process is 3474process is 3476process is 3475process is 3477
以上执行了打印了2^3次;



4.pid_t  vfork(void)

返回值:

-1           失败,并且记录到errno;

子进程返回值是0;

子进程ID  父进程中得到子进程ID作为返回值;

说明:vfork是与父进程共享地址空间,并且父进程会等待子进程执行完毕后才继续执行,

子进程有自己的pid;


5.执行文件exec族

(1) int execl(const char *path, const char *arg, ...);//l的意思是list

举例:execl("/bin/ps","ps",“-ef”,NULL);//该语句相当于shell命令:“ps   -ef”;

(2)int execlp(const char *file, const char *arg, ...);//文件名可以不用全路径;

举例:execl("ps","ps",“-ef”,NULL);//该语句相当于shell命令:“ps   -ef”;

(3)int execv(const char *path, char *const argv[]);//v是数组的意思;

举例:char*arg【】={“ps”,“-ef”,NULL};//注意:最后参数以NULL结尾;

           execv(“/bin/ps”,arg);//就可以执行同以上效果了;


6.进程的销毁

void  exit(int  status);

void  _exit(int  status);//第二个函数需要包含头文件:unistd.h

不同:exit会清空缓存;_exit不会清空缓存;

举例:

#include<stdio.h>#include<stdlib.h>int main(){    printf("hello world");    exit(0);}
执行结果:[root@localhost ~]# ./exit
                    hello world[root@localhost ~]#

#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){    printf("hello world");    _exit(0);}
执行结果:(没有打印出hello  world)
[root@localhost ~]# ./_exit

[root@localhost ~]#


7.进程等待

(1) pid_t  wait(int *status);

功能:让主进程等待子进程执行完后,主进程才开始执行;

参数:status是子进程退出时返回的状态;如果不需要知道子进程返回什么值,可以用NULL代替;

(2) pid_t waitpid(pid_t pid, int *status, int options);

参数:pid是指定主进程要等待的子进程ID;

            status是该子进程的返回值;

             option是设置的选项;

0 0
原创粉丝点击