實驗要求:實現一個遠程編譯系統
執行過程:用戶端提交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));