#include <spawn.h>
int posix_spawn(pid_t *restrict pid, const char *restrict path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *restrict attrp,
char *const argv[restrict], char *const envp[restrict]);
在main函数中调用该函数可以将一个可执行文件运行起来;如下面所示:
posix_spawn(&child_pid, "ls", NULL, NULL, argv, NULL);
执行完该函数之后,会将该目录下的ls可执行程序运行起来,会输出该目录下的文件;
argv参数可有可无,在例子中,如果没有带参数,那么直接执行ls;也可以带上参数-l,那么直接执行ls -l,则以列表的形式显示该目录下的文件;
在第二个例子中,参数是test.txt,那么对于第一个进程,则执行 ls test.txt,则输出test.txt;对于第二个进程,则执行cat test.txt输出test.txt的内容;
在例子二中吊起了两个可执行文件ls 和 cat(这两个文件是我从/bin目录下直接拷贝过来的,也可以自己生成一个可执行文件,只是这里我太懒了。。。。。)
wait(&wait_val);
刚才运行的进程的返回值输入到wait_val中;(感觉我例子二中有一点问题,第一个wait也有可能会得到的是第二个吊起的进程,不过这个例子得到的确实是正确的)
实例一:
/*************************************************************************
> File Name: useposix_spawn.cpp
> Author:
> Mail:
> Created Time: 2015年12月14日 星期一 14时21分52秒
************************************************************************/
#include <iostream>
#include <spawn.h>
#include <string.h>
#include <sys/wait.h>
#include <cstdlib>
#include <error.h>
using namespace std;
/*
#include <spawn.h>
int posix_spawn(pid_t *restrict pid, const char *restrict path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *restrict attrp,
char *const argv[restrict], char *const envp[restrict]);
*/
int main(int argc, char *argv[])
{
pid_t child_pid;
int ret;
int wait_val;
cout << "This is main process......" << endl;
ret = posix_spawn(&child_pid, "ls", NULL, NULL, argv, NULL);
if (ret != 0){
cout << "posix_spawn is error" << endl;
exit(-1);
}
wait(&wait_val);
cout << "This is main process and the wait value is " << wait_val << endl;
exit(0);
}
实例二:
/*************************************************************************
> File Name: useposix_spawn2.cpp
> Author:
> Mail:
> Created Time: 2015年12月14日 星期一 14时21分52秒
************************************************************************/
#include <iostream>
#include <spawn.h>
#include <string.h>
#include <sys/wait.h>
#include <cstdlib>
#include <error.h>
using namespace std;
/*
#include <spawn.h>
int posix_spawn(pid_t *restrict pid, const char *restrict path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *restrict attrp,
char *const argv[restrict], char *const envp[restrict]);
*/
int main(int argc, char *argv[])
{
pid_t child_pid[2];
int ret;
int wait_val[2];
cout << "This is main process......" << endl;
ret = posix_spawn(&child_pid[0], "ls", NULL, NULL, argv, NULL);
if (ret != 0){
cout << "posix_spawn is error" << endl;
exit(-1);
}
ret = posix_spawn(&child_pid[1], "cat", NULL, NULL, argv, NULL);
if (ret != 0){
cout << "posix_spawn is error" << endl;
exit(-1);
}
wait(&wait_val[0]);
cout << "This is main process and the wait value of ls is " << wait_val[0] << endl;
wait(&wait_val[1]);
cout << "This is main process and the wait value of cat is " << wait_val[1] << endl;
exit(0);
}