pipe
函数指针

父子进程通信

erhuabushuo posted @ 2012年9月12日 15:04 in C , 1293 阅读

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

int main()
{
    int data_processed;
    int file_pipes[2];
    const char some_data[] = "123";
    char buffer[BUFSIZ + 1];
    pid_t fork_result;

    memset(buffer, '\0', sizeof(buffer));

    if (pipe(file_pipes) == 0)
    {
        fork_result = fork();
        if (fork_result == -1)
        {
            fprintf(stderr, "Fork failure");
            exit(EXIT_FAILURE);
        }
        /* child */
        if (fork_result == 0)
        {
            sprintf(buffer, "%d", file_pipes[0]);
            (void)execl("pipe4", "pip4", buffer, (char *)0);
            exit(EXIT_FAILURE);
        }
        else
        {
            /* parent */
            data_processed = write(file_pipes[1], some_data,
                                   strlen(some_data));
            printf("%d - Wrote %d bytes\n", getpid(),data_processed);
        }
    }
    exit(EXIT_SUCCESS);
}

 

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

int main(int argc, char *argv[])
{
    int data_processed;
    char buffer[BUFSIZ + 1];
    int file_descriptor;

    memset(buffer, '\0', sizeof(buffer));
    sscanf(argv[1], "%d", &file_descriptor);
    data_processed = read(file_descriptor, buffer, BUFSIZ);

    printf("%d - read %d bytes: %s\n", getpid(), data_processed, buffer);
    exit(EXIT_SUCCESS);
}

30510 - Wrote 3 bytes
30511 - read 3 bytes: 123

seo service UK 说:
2024年1月15日 22:01

This specific is generally clearly basic and in addition exceptional truth alongside without a doubt reasonable and besides in fact valuable My business is seeking find ahead of time intended for this particular helpful stuff


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter