读书人

linux 过程控制

发布时间: 2012-12-26 14:39:29 作者: rapoo

linux 进程控制

获取进程ID:

pid_tgetpid(void) // 获取当前进程的进程ID

pid_tgetppid(void) // 获取父进程ID

Example:

#include <stdio.h>

#include <unistd.h>

int main(){

intpid, ppid;

pid= getpid();

ppid= getppid();

printf("pidis: %d.\n", pid);

printf("ppidis: %d\n.", ppid);

}

进程创建 - fork

pid_tfork(void)

功能:创建子进程。被调用一次,返回两次。

1. 在父进程中,fork返回新创建的子进程的pid;

2. 在子进程中,fork返回0;

3. 如果出错,fork返回一个负值。

Example:

#include <stdio.h>

#include <unistd.h>

int main(){

printf("Thecurrent pid is: %d.\n", getpid());

intpid = fork(); //创建子进程,后面的代码子进程也会允许,但是和父进程的数据空间分属不同

if(pid< 0){

perror("createchild process failed.\n");

}

elseif(pid == 0){

printf("Iam in child process, the child process is: %d.\n", getpid());

}

else{

sleep(5);

printf("Iam in parent process, the pid is: %d\n", getpid());

}

}

进程创建 - fork

pid_tvfork(void)

功能:

创建子进程。

fork和 vfork的区别:

1. fork:子进程拷贝父进程的数据段

vfork:子进程与父进程共享数据段

2. fork: 父、子进程执行的次序不确定

vfork:子进程先执行,父进程后执行

exec函数族

exec用被执行的程序替换调用它的程序。

区别:

fork创建一个新的进程,产生一个新的PID。

exec启动一个新程序,替换原有的进程,因此进程的PID不会改变。

int execl(constchar *path, const char *argument1,...)

参数:

path被执行的程序名

arg1 - argn被执行程序所需的命令行参数,含程序名。以空指针(NULL)表示结束。

#include <unistd.h>

int main(){

execl("/bin/mkdir","mkdir","/root/test_dir", NULL); //相对于mkdir /root/test_dir

}

也可以用0来结束,但是0必须转化为字符指针:

execl("/bin/mkdir","mkdir","/root/test_dir", (char *)0 );

将众参数置于数组之中来调用:execv

#include <unistd.h>

int main(){

char*argv[] = {"mkdir", "/root/test_execv", NULL };

execv("/bin/mkdir",argv);

}

system函数执行shell命令:

intsystem(const char *string);

system()会调用fork()产生子进程,由子进程来调用"/bin/sh-c string" 来执行string字符串所代表的命令,此命令执行完后随即返回原调用的进程。

system和exec的区别:

1. system() 和 exec()都可以执行进程外的命令,system是原进程上开辟了一个新的进程,但是exec用新进程(命令)覆盖了原进程。

2. system() 和 exec()都产生返回值,system的返回值并不影响原进程,但是exec的返回值影响了原进程。

Example:

#include <stdlib.h>

int main(){

system("/bin/mkdir/root/test_system");

}

wait等待子进程中断或者结束:

pid_twait(int *status);

wait()会暂停目前进程的执行,直到有信号或子进程结束。如果调用wait()时子进程已经结束,则wait()会立即返回子进程的结束状态值。子进程的状态结束值由参数status返回,如果不在意结束状态值,则status参数可以设成NULL。

#include <unistd.h>

#include <sys/wait.h>

#include <stdio.h>

int main(){

pid_tpf = fork();

if(pf== 0){

printf("childprocess start.\n");

sleep(5); //睡眠5s

printf("childprocess over.\n");

}

elseif (pf > 0){

printf("parentprocess start.\n");

wait(NULL); //等待子进程退出

printf("parentprocess over.\n");

}

return0;

}

读书人网 >UNIXLINUX

热点推荐