⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test5.1.c

📁 这个是学习嵌入式开发的重要例子
💻 C
字号:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <errno.h>#include <sys/stat.h>#include <fcntl.h>#define BUFFER_SIZE	1024#define	FIFO	"/tmp/fifo.test"void child_process_main(void);void producer_process_main(void);int main(int argc, char **argv){  umask(0);  // int mkfifo(const char *path, mode_t mode);  if (mkfifo(FIFO, 0644) < 0)  {    fprintf(stderr, "mkfifo() failed: %s\n", strerror(errno));    if (errno == EEXIST)    {      fprintf(stdout, "The fifo file is alreay existed.\n");    }    else    {      exit(1);    }  }  producer_process_main();  //unlink(FIFO);  return 0;}void producer_process_main(void){  int fd;  //int open(const char *pathname, int flags);  //int open(const char *pathname, int flags, mode_t mode);  //fd = open(FIFO, O_WRONLY | O_NONBLOCK);  fd = open(FIFO, O_WRONLY);  sleep(10);  if (fd < 0)  {    fprintf(stderr, "[%d]open FIFO %s for writting failed: %s\n", getpid(), FIFO, strerror(errno));    return;  }  else  {    fprintf(stdout, "[%d]open FIFO %s for writting successed, fd = %d\n", getpid(), FIFO, fd);    sleep(10);    //close(fd);  }  pid_t pid;  pid = getpid();  fprintf(stdout, "[%d]Write data to pipe, fd = %d\n", getpid(), fd);  char buf[BUFFER_SIZE];  char wbuf[BUFFER_SIZE];  memset(buf, 0, BUFFER_SIZE);  // char *fgets(char *restrict s, int n, FILE *restrict stream);  if (fgets(buf, BUFFER_SIZE, stdin) == NULL)  {    fprintf(stdout, "[%d]Read failed from stdin: %s\n", getpid(), strerror(errno));    // FIXME: handle read from stdin failed  }  else  {    // ssize_t write(int fildes, const void *buf, size_t nbyte);    ssize_t n;    int length;    length = strlen(buf);    memset(wbuf, 0, BUFFER_SIZE);    // int snprintf(char *str, size_t size, const char *format, ...);    snprintf(wbuf, BUFFER_SIZE, "%08d%s", length, buf);    fprintf(stdout, "[%d]Composed to-be-sent buffer: %s\n", pid, wbuf);    n = write(fd, wbuf, strlen(wbuf));    fprintf(stdout, "[%d]Write %d bytes to pipe.\n", pid, n);  }  close(fd);}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -