溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

[Linux管道和IPC]管道的實際應用1

發布時間:2020-06-30 15:02:40 來源:網絡 閱讀:454 作者:銀河星君 欄目:編程語言
/*
主進程創建2個子進程,子進程1每隔1秒向子進程2發送一個
字符串,子進程接收到該字符串之后將其寫入一個指定的文件
*/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>

//以下為主函數
int main(int argc,char *argv[])
{
  pid_t pid1,pid2;            //進程的ID
  int fd;                     //文件描述符
  char writebuf[] = "this is a test!\n";   //待寫入字符串
  char readbuf[25];            //讀緩沖區
  int writecounter = 0;       //用于記錄寫入的偏移量
  int temp = 0,seektemp = 0,j = 0; //都是用于計算文件偏移的臨時變量
  int pipefd[2];              //管道的文件描述符
  if (argc != 2)              //如果參數不正確
  {
    printf("請輸入正確的文件參數。\n");
    return 0;
  }
  fd = open(*(argv+1),O_RDWR|O_CREAT,S_IRWXU); //打開或者創建一個文件
  if(pipe(pipefd) < 0)        //如果創建管道失敗
  {
    printf("創建管道失敗。\n");
    exit(0);                  //退出
  }
  pid1 = fork();              //調用fork創建一個新的進程
  if(pid1 != 0)                //主進程
  {
    pid2 = fork();             //創建第二個子進程
    if(pid2 != 0)             //主進程
    {
      close(pipefd[0]);          //關閉管道
      close(pipefd[1]);
    }
    else                       //這是子進程2的操作
    {
      close(pipefd[1]);
      while(1)
      {
        read(pipefd[0],readbuf,sizeof(writebuf));   //讀管道 
        printf("這是子進程2.\n");     //屏幕輸出提示
        if(writecounter == 0)        //第一次寫入
        {
          temp = write(fd,readbuf,strlen(readbuf));  //寫入數據
          seektemp = lseek(fd,0,SEEK_CUR);             //獲得當前偏移量
          writecounter++;
        }
        else
        {
          j = strlen(readbuf)*writecounter;
          seektemp = lseek(fd,j,SEEK_SET);
          temp = write(fd,readbuf,strlen(writebuf));
          writecounter++;
        }
      }
    }
  }
  else                       //子進程
  {
    close(pipefd[0]);
    while(1)
    {
      sleep(1);
      write(pipefd[1],writebuf,sizeof(writebuf));   //將字符串寫入管道
    }
  }
}


向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女