【问题标题】:Extreme Confusion on Forks and Execlp对 Forks 和 Execlp 的极度困惑
【发布时间】: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


    【解决方案1】:

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

    execlp("./worker", "worker", arrayofNum[0], arrayofNum[1]);
    

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

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

    其次,拨打waitpid(2)之后你需要做的事情:

    if (WIFEXITED(status))
        code = WEXITSTATUS(status);
    

    【讨论】:

    • 感谢 cnicutar 如此及时的回复。我添加了必要的更正,但是当我 cout
    • @JohnathanMonaco 您可能传递的参数错误。
    • 这是 execlp: execlp("./worker", "worker", arrayofNum[0], arrayofNum[1], NULL);和另一个等待(&status); if (WIFEXITED(status)) { value = WEXITSTATUS(status); } } cout
    • @JohnathanMonaco 你没在听 :-)) 你不能通过arrayofNum。你需要传递一个char *
    • 哦,哇,我很抱歉!太感谢了!只要我将它们保留为字符,我是否仍可以将它们作为单独的传递。也许比如 execlp("./worker", "worker", arrayofChar[0], arrayofChar[1], NULL);或者应该是一个数组。非常感谢您对我的耐心,这是我第一次体验这种编程。
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 2018-01-09
    • 1970-01-01
    • 2016-05-21
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多