Linux網路進程通訊實驗小結__Linux

來源:互聯網
上載者:User

實驗要求:實現一個遠程編譯系統

執行過程:用戶端提交c語言代碼檔案,在服務端編譯串連,服務端執行檔案後把結果返回給用戶端。

細節說明:

(1)在執行外部命令時,要在該函數下建立子進程。 if ((cpid = fork()) != 0 )
... {
      return 0;
}
else
... {
      execl(argv[0], argv[1], argv[2], (char *)0);
      exit(0);
}

(2)服務端在接收用戶端傳送的二進位流時,為了同步,需要等待;否則,經過實驗,會造成服務端資料丟失。 while ( ! flag)
... {
     if(recv(tsockfd, package, 1024, 0)<0)
     ...{
          perror("recv");
          exit(1);
     }
     else
     ...{
          flag=1;
     }
}

(3)由於socket傳輸的是二進位流,所以在接收字串時要在資料結尾增加“字串結束符”。 numb = recv(tsockfd, str,  10 ,  0 );
if (numb < 0 )
... {
     perror("recv");
     exit(1);
}
str[numb] = '/0';

(4)服務端接收用戶端的資料時,除了建立子進程外,還需要通過管道進行進程內通訊,用來傳送子進程啟動並執行結果。 if (pipe(fd) ==- 1 )
... {
     printf("create pipe error! ");
     exit(1);
}
switch (child_pid = fork())
... { 
     case 0:
     ...{
          close(fd[0]);
          if(put()==0)
          ...{
               sprintf(reply, "upload successfully!");
               write(fd[1], reply, strlen(reply));
          }
          else
          ...{
               sprintf(reply, "upload error!");
               write(fd[1], reply, strlen(reply));
          }
          exit(0);
          break;
     }
     case -1:
     ...{
         perror("fork error");
         break;
     }
     default:
     ...{
           int len;
           close(fd[1]);
           len=read(fd[0], reply, sizeof(reply));
          

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.