【发布时间】:2013-01-25 15:01:39
【问题描述】:
这是我的第一篇文章。 我有一个任务是使用 fork 创建多个进程,然后使用 execlp 运行另一个程序来添加 2 个数字。
我遇到的问题是我们应该在 execlp 中使用 exit() 调用来返回小整数。这是一种糟糕的交流方式,但为了这个计划,这是我们应该做的。
这是我的“协调员”计划
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
using namespace std;
int main (int argc,char* argv[])
{
const int size = argc-1;
int sizeArray = 0;
int numofProc =0;
int arrayofNum[size];
int status;
int value;
for(int y=1; y<argc; y++)
{
arrayofNum[y-1] = atoi(argv[y]);
sizeArray++;
}
if(sizeArray % 2 !=0)
{
arrayofNum[sizeArray] = 0;
sizeArray++;
}
numofProc = sizeArray/2;
//declaration of a process id variable
pid_t pid;
//fork a child process is assigned
//to the process id
pid=fork();
//code to show that the fork failed
//if the process id is less than 0
if(pid<0)
{
cout<<"Fork Failed";// error occurred
exit(-1); //exit
}
//code that runs if the process id equals 0
//(a successful for was assigned
else
if(pid==0)
{
//this statement creates a specified child process
execlp("./worker", "worker", arrayofNum[0], arrayofNum[1]);//child process
}
//code that exits only once a child
//process has been completed
else
{
waitpid(pid, &status, 0);
cout<<status;
}
//main
}
这里是execlp进程
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
int main(int argc, char* argv[])
{
int arrayofNum[argc-1];
arrayofNum[0] = atoi(argv[1]);
arrayofNum[1] = atoi(argv[2]);
int sum = arrayofNum[0] + arrayofNum[1];
exit(sum);
}
我的问题是不管我做什么,状态总是打印一个 0,我不知道如何检索从工作进程返回的总和。
我的教授告诉我““只有状态的高字节才会有工人返回的值。你需要提取它。它可以通过多种方式完成。 ""
简而言之,我的问题是,如何检索从我的工作进程发送的“总和”。
拜托,我很困惑,已经睡了两个晚上想知道这个
谢谢,
约翰
【问题讨论】:
标签: c++ linux operating-system fork exe