How to send integer with pipe between two processes!

前端 未结 4 1720
情深已故
情深已故 2021-02-05 12:12

I am trying to send an integer with pipe in a POSIX system but write() function is working for sending string or character data. Is there any way to send integer wi

相关标签:
4条回答
  • 2021-02-05 12:20

    Either send a string containing the ASCII representation of integer e.g., 12345679, or send four bytes containing the binary representation of int, e.g., 0x00, 0xbc, 0x61, 0x4f.

    In the first case, you will use a function such as atoi() to get the integer back.

    0 讨论(0)
  • 2021-02-05 12:24

    The safe way is to use snprintf and strtol.

    But if you know both processes were created using the same version of compiler (for example, they're the same executable which forked), you can take advantage of the fact that anything in C can be read or written as an array of char:

    int n = something();
    write(pipe_w, &n, sizeof(n));
    
    int n;
    read(pipe_r, &n, sizeof(n));
    
    0 讨论(0)
  • 2021-02-05 12:28

    Below one works fine for writing to pipe and reading from pipe as:

    stop_daemon =123;
    res = write(cli_pipe_fd_wr, &stop_daemon, sizeof(stop_daemon));
    ....
    res = read(pipe_fd_rd, buffer, sizeof(int));
    memcpy(&stop_daemon,buffer,sizeof(int));
    printf("CLI process read from res:%d status:%d\n", res, stop_daemon);
    

    output:

    CLI process read from res:4 status:123
    
    0 讨论(0)
  • 2021-02-05 12:36

    Aschelpler's answer is right, but if this is something that can grow later I recommend you use some kind of simple protocol library like Google's Protocol Buffers or just JSON or XML with some basic schema.

    0 讨论(0)
提交回复
热议问题