首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Forks和Execlp上的极端混乱

Forks和Execlp上的极端混乱
EN

Stack Overflow用户
提问于 2013-02-10 17:41:19
回答 1查看 385关注 0票数 0

这是我的第一篇文章。我有一个任务是使用fork创建多个进程,然后使用execlp运行另一个程序来添加2个数字。

我遇到的问题是,我们应该在execlp中使用exit()调用来返回小整数。这是一种糟糕的沟通方式,但为了这个程序,这是我们应该做的。

这是我的“协调器”程序

代码语言:javascript
复制
#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进程

代码语言:javascript
复制
#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,我不知道如何检索从工作进程返回的总和。

我的教授告诉我,“”只有状态的高位字节才会有worker返回的值。你需要把它提取出来。这可以通过许多方法来完成。"“

简而言之,我的问题是,如何检索从工作进程发送的"sum“。

求求你,我很困惑,已经两个晚上没睡了,一直在想这个问题

谢谢,

约翰

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-10 17:45:30

首先,您需要将字符串传递给您的程序,但是您可以这样说:

代码语言:javascript
复制
execlp("./worker", "worker", arrayofNum[0], arrayofNum[1]);

arrayofNum是一个整数数组。此外,对于execlp,您还需要传递一个NULL作为最后一个参数。The standard说:

由arg0,... 表示的参数是指向以null结尾的字符串的指针。这些字符串应构成新过程映像可用的参数列表。列表以空指针结束。

其次,在调用waitpid(2)之后,您需要执行以下操作:

代码语言:javascript
复制
if (WIFEXITED(status))
    code = WEXITSTATUS(status);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14796410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档