Linux多进程编程学习(Part 1)

来源:互联网 发布:网络编辑工具箱 编辑:程序博客网 时间:2024/05/29 04:02

一、Linux多进程编程的系统调用函数

    1、system系统调用

        system系统调用Shell来启动一个程序,运行由字符串参数指定的命令并等待该命令的完成。但由于不同的系统Shell的环境不同,system系统调用的限制较大,它的作用等同于$/bin/sh -c command。

#include <stdlib.h>int system(const char *command)
如果无法用Shell来运行命令,返回错误代码127,如果是其它错误则返回-1,否则返回命令的退出码。

我们来看一个例子:

#include <stdlib.h>#include <iostream>using namespace std;int main(){    int ret;    cout << "Running another process with system()" << endl;    system("ps ax");    cout << "Done." << endl;    return 0;}
我们看到在system调用之后会输出Done,说明main函数在等待system调用完成之后才会继续运行。

2、exec函数组

与system调用不同的是,exec函数组会将程序的执行从一个程序切换到另一个程序,而原程序就不再继续运行了,因此它比system要高效。

#include <unistd.h>int execl(const char *path, const char *arg0, ..., (char *)0);int execlp(const char *file, const char *arg0, ..., (char *)0);int execle(const char *path, const char *arg0, ..., (char *)0, char *const envp[]);int execv(const char *path, char *const argv[]);int execvp(const char *file, char *const argv[]);int execve(const char *path, char *argv[], char *const envp[]);
含有字母"l"的函数其参数数量是可变的,运行程序的参数通过可变数量参数指定(注意,参数需包括即将运行的命令名称,相当于argv[0])

含有字母"v"的函数,运行命令的参数通过形参argv指定。

以字母"p"结尾的函数会在PATH环境变量中查找程序名,以字母"e"结尾的函数,通过最后一个参数指定程序运行的环境变量,即形参envp。

用法如下:

#include <unistd.h>char *const ps_argv[] = {"ps", "ax", 0};char *const ps_envp[] = {"PATH=/bin:/usr/bin", "TERM=console", 0};// possible calls to exec functionsexecl("/usr/bin/ps", "ps", "ax", 0);execlp("ps", "ps", "ax", 0);execle("bin/ps", "ps", "ax", 0, ps_envp);// passes own environmentexecv("/bin/ps", ps_argv);execvp("ps", ps_argv);execve("/bin/ps", ps_argv, ps_envp);
由exec启动的新进程继承了原进程的很多属性,一般情况下它不返回值,出错时返回-1,并设置errno的值。


3、fork系统调用

通过系统调用fork创建一个新的进程,它复制当前进程,在进程表中创建一个新的表项,新进程的许多属性与当前进程是相同的。但新进程有自己的数据空间,文件描述符等。

#include <unistd.h>#include <sys/types.h>pid_t fork();
在父进程中fork调用返回子进程的PID,在子进程中它返回0,当出错时返回-1并设置errno。我们可以通过检测fork调用的返回值来确定接下来的代码是在父进程还是在子进程中运行:

#include <sys/types.h>#include <sys/wait.h>#include <unistd.h>#include <cstdio>#include <cstdlib>#include <iostream>#include <string>using namespace std;int main(){pid_t new_pid;string message;int n;cout << "Fork program starting" << endl;new_pid = fork();switch(new_pid){case -1:cerr << "Fork failed" << endl;return 0;case 0:message = "This is the child";n = 5;break;default:message = "This is the parent";n = 3;break;}for(; n > 0; n--){cout << message << endl;sleep(1);}return 0;}
运行程序得到的输出是parent打印了3次,child打印了5次,但打印的次序很混乱,这时候就要采取方法来控制父子进程之间的同步了,这个以后再做笔记。

参考书目:

APUE(第三版)

Linux程序设计(第四版)

0 0
原创粉丝点击