web-dev-qa-db-ja.com

パイプを使用して親と子の間で整数値を渡す

Pipe()を使用して2つのプロセス間で整数値を渡す方法について少し混乱しています。

私のプログラムでは、最初にパイプを作成し、次にフォークします。私は「2本」のパイプを持っていると思いますか?

私が理解していることから、これは私の割り当てです。私の親は、特定の操作のために整数値「i」をチェックするforループを通過し、カウント変数を増やし、値を配列に保存します。各チェックの後、親は整数値「i」をパイプ経由で子供に渡す必要があります。私の子供はその整数値を使用し、値をチェックし、カウント変数を増やし、結果を[共有?]配列に保存する必要があります。最終的に子は、最終的なカウントを親に返します。親は、2つのカウントと「共有」配列を出力します。

->共有配列が必要なのか、結果を保存する必要があるのか​​はわかりません。カウントのみが必要な場合があります。宿題はあいまいで、教授からの返答を待っています。また;プロセス間で共有配列を行うこともできますか?それは私にとって何らかの問題の始まりのように聞こえます。

->私の質問は次のとおりです。整数にパイプを使用するにはどうすればよいですか?私はそれらを文字配列でのみ見ましたが、以前の答えはこれが可能または合法だとは思わないようです。よく分かりません。私が見つけられる解決策はありませんでした。

->単方向パイプを使用して整数を子に渡すにはどうすればよいですか?そして、子供は何かを返しましたか?どうすれば... 2つのパイプを区別できるかわかりません。 「いくつかのあいまいな問題」を回避するために、各パイプの未使用部分を1つ閉じる必要があることを「知っています」[または知っていると思います]。

愚かな質問でごめんなさい。このクラスでは、プロセス(フォークを除く)やパイプ(まったく)をまだ教えていません。したがって、どこから始めればよいのかわかりません。

ここに私のコードの一部があります-それはきれいではなく、機能せず、私はそれを期待していません。これは、シェルプレースホルダーのようなものです。パイプの使用方法を理解したら、おそらくコードを意味のあるものにします。

int main(void)
{
int fd[2];
pid_t childpid;
pid_t parentpid;
int i;
int threecount = 0;
int fivecount = 0;;
int results [MAXSIZE];

parentpid = getpid(); //Get current process ID number

pipe(fd);
childpid = fork(); 

if(childpid == 0){
close(fd[0]); //Closing this for some other reason

}
int j = 0;

if(childpid > 0)
close(fd[1]); //Closing this for some reason


if( childpid == -1 )
{
    perror("Failed to fork\n");
    return 1;
}
if (childpid > 0)
{
    for(i = 1; i < MAXSIZE;i++)
    {
        if(i % 5 == 0)
        {
            fivecount++;
            i = results[j];
            j++; 
            wait(NULL);
        }
    }
}
else if (childpid == 0)
    {
        if(i % 3 == 0) //This i here should probably be the i value above, piped to the child
        {
            threecount++;
            i = results[j];  //This should be part of th pipe
            j++;    //Trying to keep count of that shared array, not really the right way to do it though.
        }

    }
    printf("%d  %d  \n", fivecount,threecount);
    return 0;

}

17
user1741874

これは、パイプを使用してintを親から子プロセス(fork()から起動された子プロセス)に送信するために必要なサンプルであるため、サンプルとほぼ同じです(エラーチェックはありません)。 (明らかに)データの送信およびの受信はより複雑になりますが、私はすべてを行うことはできませんあなたのため。これは、子からint(実際には、intが使用するバイト数)を分岐して待機します。

更新:この後、send + response双方向通信の例を追加しました。詳細については、2番目のコードリストを参照してください。

それが役に立てば幸い。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int fd[2];
    int val = 0;

    // create pipe descriptors
    pipe(fd);

    // fork() returns 0 for child process, child-pid for parent process.
    if (fork() != 0)
    {
        // parent: writing only, so close read-descriptor.
        close(fd[0]);

        // send the value on the write-descriptor.
        val = 100;
        write(fd[1], &val, sizeof(val));
        printf("Parent(%d) send value: %d\n", getpid(), val);

        // close the write descriptor
        close(fd[1]);
    }
    else
    {   // child: reading only, so close the write-descriptor
        close(fd[1]);

        // now read the data (will block)
        read(fd[0], &val, sizeof(val));
        printf("Child(%d) received value: %d\n", getpid(), val);

        // close the read-descriptor
        close(fd[0]);
    }
    return 0;
}

出力:

Parent(5943) send value: 100
Child(5945) received value: 100

更新: 2つのパイプセットを使用してsend + responseを含めるように拡張

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

// some macros to make the code more understandable
//  regarding which pipe to use to a read/write operation
//
//  Parent: reads from P1_READ, writes on P1_WRITE
//  Child:  reads from P2_READ, writes on P2_WRITE
#define P1_READ     0
#define P2_WRITE    1
#define P2_READ     2
#define P1_WRITE    3

// the total number of pipe *pairs* we need
#define NUM_PIPES   2

int main(int argc, char *argv[])
{
    int fd[2*NUM_PIPES];
    int val = 0, len, i;
    pid_t pid;

    // create all the descriptor pairs we need
    for (i=0; i<NUM_PIPES; ++i)
    {
        if (pipe(fd+(i*2)) < 0)
        {
            perror("Failed to allocate pipes");
            exit(EXIT_FAILURE);
        }
    }

    // fork() returns 0 for child process, child-pid for parent process.
    if ((pid = fork()) < 0)
    {
        perror("Failed to fork process");
        return EXIT_FAILURE;
    }

    // if the pid is zero, this is the child process
    if (pid == 0)
    {
        // Child. Start by closing descriptors we
        //  don't need in this process
        close(fd[P1_READ]);
        close(fd[P1_WRITE]);

        // used for output
        pid = getpid();

        // wait for parent to send us a value
        len = read(fd[P2_READ], &val, sizeof(val));
        if (len < 0)
        {
            perror("Child: Failed to read data from pipe");
            exit(EXIT_FAILURE);
        }
        else if (len == 0)
        {
            // not an error, but certainly unexpected
            fprintf(stderr, "Child: Read EOF from pipe");
        }
        else
        {
            // report what we received
            printf("Child(%d): Received %d\n", pid, val);

            // now double it and send it back
            val *= 2;

            printf("Child(%d): Sending %d back\n", pid, val);
            if (write(fd[P2_WRITE], &val, sizeof(val)) < 0)
            {
                perror("Child: Failed to write response value");
                exit(EXIT_FAILURE);
            }
        }

        // finished. close remaining descriptors.
        close(fd[P2_READ]);
        close(fd[P2_WRITE]);

        return EXIT_SUCCESS;
    }

    // Parent. close unneeded descriptors
    close(fd[P2_READ]);
    close(fd[P2_WRITE]);

    // used for output
    pid = getpid();

    // send a value to the child
    val = 42;
    printf("Parent(%d): Sending %d to child\n", pid, val);
    if (write(fd[P1_WRITE], &val, sizeof(val)) != sizeof(val))
    {
        perror("Parent: Failed to send value to child ");
        exit(EXIT_FAILURE);
    }

    // now wait for a response
    len = read(fd[P1_READ], &val, sizeof(val));
    if (len < 0)
    {
        perror("Parent: failed to read value from pipe");
        exit(EXIT_FAILURE);
    }
    else if (len == 0)
    {
        // not an error, but certainly unexpected
        fprintf(stderr, "Parent(%d): Read EOF from pipe", pid);
    }
    else
    {
        // report what we received
        printf("Parent(%d): Received %d\n", pid, val);
    }

    // close down remaining descriptors
    close(fd[P1_READ]);
    close(fd[P1_WRITE]);

    // wait for child termination
    wait(NULL);

    return EXIT_SUCCESS;
}

(たとえば、gcc thisfile.c -o test

出力

Parent(2794): Sending 42 to child
Child(2797): Received 42
Child(2797): Sending 84 back
Parent(2794): Received 84
25
WhozCraig