5.29 Linux进程间通信新增API:eventfd

1、实验代码

#include <sys/eventfd.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>             /* Definition of uint64_t */

#define handle_error(msg) \
    do { perror(msg); exit(EXIT_FAILURE); } while (0)

int main (int argc, char *argv[])
{
    int fd_event, j;
    uint64_t u;
    ssize_t s;

    if (argc < 2) 
    {
        fprintf (stderr, "Usage: %s <num>...\n", argv[0]);
        exit (EXIT_FAILURE);
    }

    fd_event = eventfd(0, EFD_SEMAPHORE);
    if (fd_event == -1)
        handle_error ("eventfd");

    switch (fork()) 
    {
        case 0:
            sleep (1);
            for (j = 1; j < argc; j++) 
            {
                printf ("Child writing %s to fd_event\n", argv[j]);
                u = strtoull (argv[j], NULL, 0);
                    /* strtoull() allows various bases */
                s = write (fd_event, &u, sizeof(uint64_t));
                if (s != sizeof(uint64_t))
                    handle_error ("write");
            }
            printf ("Child completed write loop\n");
            exit (EXIT_SUCCESS);

        default:
            //  sleep (2);

            printf ("Parent about to read\n");
            s = read (fd_event, &u, sizeof(uint64_t));
            if (s != sizeof(uint64_t))
                handle_error ("read");
            printf ("Parent read %llu (0x%llx) from fd_event\n",
                (unsigned long long) u, (unsigned long long) u);

            s = read (fd_event, &u, sizeof(uint64_t));
            if (s != sizeof(uint64_t))
                handle_error ("read");
            printf ("Parent read %llu (0x%llx) from fd_event\n",
                (unsigned long long) u, (unsigned long long) u);

            s = read (fd_event, &u, sizeof(uint64_t));
            if (s != sizeof(uint64_t))
                handle_error ("read");
            printf ("Parent read %llu (0x%llx) from fd_event\n",
                (unsigned long long) u, (unsigned long long) u);
            exit (EXIT_SUCCESS);

        case -1:
            handle_error ("fork");
    }
}
// ./a.out 1 2 3 4 5 6 7 8 9

2、实验结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值