《TCP/IP网络编程》第11章 进程间通信

92 篇文章 19 订阅
34 篇文章 3 订阅

进程间通信(inter Process Communication)意味着两个不同进程间可以交换数据。

管道

管道并非进程的资源,而是和套接字一样,属于操作系统(操作系统的内存空间,进程可以访问)。

#include <unistd.h>
//成功0,失败-1
int pipe(int filedes[2]);
//files[0],接收文件描述符
//files[1],发送文件描述符

通过管道实现进程间通信

11.pipe1.c

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

#define BUF_SIZE 30

int main(int argc, char *argv[])
{
    int fds[2];
    pipe(fds);

    pid_t pid = fork();
    if (pid == 0)
    {
        char str[] = "Who are you?";
        write(fds[1], str, sizeof(str));
    }
    else
    {
        char buf[BUF_SIZE];
        read(fds[0], buf, BUF_SIZE); // 阻塞
        puts(buf);
    }

    return 0;
}

// gcc 11.pipe1.c -o 11.pipe1 && ./11.pipe1

通过管道实现进程间双向通信

11.pipe2.c
#include <stdio.h>
#include <unistd.h>

#define BUF_SIZE 30

int main(int argc, char *argv[])
{
    char buf[BUF_SIZE];

    int fds[2];
    pipe(fds);

    pid_t pid = fork();
    if (pid == 0)
    {
        char str1[] = "Who are you?";
        write(fds[1], str1, sizeof(str1));
        sleep(2); // 防止管道内写入数据被本进程读取
        read(fds[0], buf, BUF_SIZE);
        printf("Child proc output: %s\n", buf);
    }
    else
    {
        char str2[] = "Thank you for your message";
        read(fds[0], buf, BUF_SIZE);
        printf("Parent proc output: %s\n", buf);
        write(fds[1], str2, sizeof(str2));
        sleep(3); // 防止父进程终止时,弹出命令提示符
    }

    return 0;
}

// gcc 11.pipe2.c -o 11.pipe2 && ./11.pipe2
11.pipe3.c
#include <stdio.h>
#include <unistd.h>

#define BUF_SIZE 30

int main(int argc, char *argv[])
{
    char buf[BUF_SIZE];

    int fds1[2];
    pipe(fds1);

    int fds2[2];
    pipe(fds2);

    pid_t pid = fork();
    if (pid == 0)
    {
        char str1[] = "Who are you?";
        write(fds1[1], str1, sizeof(str1));
        read(fds2[0], buf, BUF_SIZE);
        printf("Child proc output: %s\n", buf);
    }
    else
    {
        char str2[] = "Thank you for your message";
        read(fds1[0], buf, BUF_SIZE);
        printf("Parent proc output: %s\n", buf);
        write(fds2[1], str2, sizeof(str2));
        sleep(3); // 防止父进程退出后弹出命令提示符
    }

    return 0;
}

// gcc 11.pipe3.c -o 11.pipe3 && ./11.pipe3

保存消息的回声服务器

11.echo_storeserver.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/wait.h>

#define PORT 9999
#define BUF_SIZE 30

void error_handling(const char *message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

void read_childprod(int sig)
{
    int status;
    pid_t pid = waitpid(-1, &status, WNOHANG);
    printf("removed proc id: %d\n", pid);
}

int main(int argc, char *argv[])
{
    struct sigaction act;
    act.sa_handler = read_childprod;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    int state = sigaction(SIGCHLD, &act, 0);

    int serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    if (serv_sock == -1)
        error_handling("socket() error");

    int opt = 1;
    if (setsockopt(serv_sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt)) == -1)
        error_handling("setsockopt() error");

    socklen_t addr_size = sizeof(struct sockaddr_in);

    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, addr_size);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(PORT);

    if (bind(serv_sock, (struct sockaddr *)&serv_addr, addr_size) == -1)
        error_handling("bind() error");

    if (listen(serv_sock, 5) == -1)
        error_handling("listen() error");

    int fds[2];
    pipe(fds);

    pid_t pid = fork();
    if (pid == 0)
    {
        close(serv_sock);

        FILE *fp = fopen("echomsg.txt", "wr");
        for (int i = 0; i < 3; i++)
        {
            char msgbuf[BUF_SIZE];
            int len = read(fds[0], msgbuf, BUF_SIZE);
            fwrite((void *)msgbuf, 1, len, fp);
        }
        fclose(fp);

        return 0;
    }

    while (1)
    {
        struct sockaddr_in clnt_addr;
        int clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_addr, &addr_size);
        if (clnt_sock == -1)
            continue;
        else
            puts("new client connected...");

        pid = fork();
        if (pid == -1)
        {
            close(clnt_sock);

            continue;
        }
        else if (pid == 0)
        {
            close(serv_sock);

            char buf[BUF_SIZE];
            int str_len;
            while ((str_len = read(clnt_sock, buf, BUF_SIZE)) != 0)
            {
                write(clnt_sock, buf, str_len);
                write(fds[1], buf, str_len);
            }

            close(clnt_sock);
            puts("client disconnected...");
            return 0;
        }
        else
        {
            close(clnt_sock);
        }
    }

    close(serv_sock);

    return 0;
}

// gcc 11.echo_storeserver.c -o 11.echo_storeserver && ./11.echo_storeserver
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值