Linux pipe通信 用法

5-06 1,091 views

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
    int result = -1;
    int fd[2];
    int nbytes;
    pid_t pid;
    char hello[] = "Hello World, my pipe";
    char readBuffer[100];
    int *read_fd = &fd[0];
    int *write_fd = &fd[1];

    memset(readBuffer, 0, sizeof(readBuffer));

    result = pipe(fd);
    if (-1 == result)
    {
        printf("fail to create pipe\n");
        return -1;
    }

    pid = fork();
    printf("pid = %d\n", pid);

    if (-1 == pid)
    {
        printf("fail to work\n");
        return -1;
    }

    if(0 == pid)
    {
        close(*read_fd);
        result = write(*write_fd, hello, strlen(hello));
        return 0;
    }
    else
    {
        close(*write_fd);
        printf("sizeof(readBuffer) = %lu\n", sizeof(readBuffer));
        nbytes = read(*read_fd, readBuffer, sizeof(readBuffer));
        printf("the parent received %d bytes data: %s\n", nbytes, readBuffer);
    }

    return 0;
}

线程间通信

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>

typedef struct _message{
    int arg;
    char* msg;
}message;

static int fd[2];

void mythread()
{
    while(1){
        message msg;
        read(fd[0], &msg, sizeof(message));
        printf("read message: %s, arg = %d\n", msg.msg, msg.arg);
    }
}

int main(void)
{
    int result;
    pthread_t id1;  

    result = pipe(fd);
    if(-1 == result){
        printf("faild to create pipe");
    }

   int ret = pthread_create(&id1, NULL, (void*)mythread, NULL);

    if(ret)

    {

        printf("create pthread error!\n");

         return  -1; 

    }

    int i = 10;
    while(1){
        char* hello = "hello world";
        message msg;
        msg.arg = i++;
        msg.msg = hello;
        write(fd[1], &msg, sizeof(msg));
        printf("write message and sleep ... \n");
        sleep(1);
    }

}

COM in plain C

https://www.codeproject.com/Articles/13601/COM-in-plain-C

阅读全文

A Brief Intro to Input Method Framework, Linux IME, and XIM

https://tedyin.com/posts/a-brief-intro-to-linux-input-method-framework/ There are chances one need an input method editor (IME). For CJK users, su...

阅读全文

使用Visual studio查看exe或DLL文件的依赖项

事先准备:只要 Visual Studio 任何版本即可。 点击开始 -> 程序 -> Visual Studio对应的版本,打开Visual Studio Tools -> 选择 命令提示 进入命...

阅读全文

1 条评论

欢迎留言