C++学习笔记40:进程应用

进程创建

system()函数:用于在程序中执行一条命令

如果shell不能运行,返回127,如果发生其他错误返回-1;

例子:int ret_val = system(“ls -l /”);

fork()函数:创建当前进程的副本作为子进程

原型:pid_t fork();

返回值为0(新创建的子进程)和子进程的PID(父进程)

//使用fork()函数创建进程的副本
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main()
{
    cout << "the main program process ID is" << (int)getpid() << endl;
    pid_t child_pid = fork();
    if (child_pid != 0)
    {
        cout << "this is the parent process,with id" << (int)getpid() << endl;
        cout << "the child's process ID is " << (int)child_pid << endl;
    }
    else
    {
        cout << "this is the child process,with id " << (int)getpid() << endl;
    }
    return 0;
}

执行命令

  exec()函数簇:不同情况,执行不同的exec()函数

基本模式:在程序中调用fork()创建一个子进程,然后调用exec()在子进程中执行命令

#include <iostream>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>

int spawn(char *program, char **args);
int main()
{
    char *args[] = { "ls","-l","/",NULL };
    spawn("ls", args);
    cout << "done" << '
';
    return 0;
}

//创建一个子进程运行新程序
//program为程序名,arg_list为程序的参数列表;返回值为子进程id
int spawn(char * program, char **args)
{
    pid_t child_pid = fork();     //复制进程
    if (child_pid ! = 0)          //此为父进程
    {
        return child_pid;
    }
    else                          //此为子程序
    {
        execvp(program, args);    //执行程序,按路径查找
        //只有发生错误时,该函数才返回
        std::cerr << "Error occurred when executing execvp.
";
        abort();
    }
}
怕什么真理无穷,进一寸有一寸的欢喜。---胡适
原文地址:https://www.cnblogs.com/hujianglang/p/6271057.html