0

これは私の最初の投稿です。フォークを使用して複数のプロセスを作成し、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を出力していることです。ワーカープロセスから返された合計を取得する方法がわかりません。

私の教授は私に「ステータスの上位バイトだけがワーカーによって返される値を持つでしょう。抽出する必要があります。それは多くの方法で行うことができます。""

一言で言えば、私の質問は、ワーカー プロセスから送信されている「合計」を取得するにはどうすればよいかということです。

どうか、私はとても混乱しており、これについて疑問に思って 2 晩起きていました

ありがとう、

ジョン

4

1 に答える 1

3

まず、文字列をプログラムに渡す必要がありますが、次のように言います。

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

AndarrayofNumは整数の配列です。NULLまた、execlpでは、最後の引数としてa も渡す必要があります。標準は次のように述べています。

arg0,... で表される引数は、ヌル終了文字列へのポインタです。これらの文字列は、新しいプロセス イメージで使用できる引数リストを構成します。リストは null ポインターで終了します

第二に、電話をかけた後、次のことwaitpid(2)を行う必要があります。

if (WIFEXITED(status))
    code = WEXITSTATUS(status);
于 2013-02-10T09:45:29.610 に答える