0
我有一個家庭作業,需要使用管道在進程之間發送一串字符串。如何使用管道發送動態分配的字符串
當我發送編譯時間從子進程到使用管道的主進程創建的字符串,它被成功發送。這是我在主要和子過程中所做的。
子過程:
char* str ="from child";
int lengthOfString=strlen(str)+1;//+1 for null terminator
write(pipes[0][1],&lengthOfString,sizeof(int));//send the length of string beforehand
write(pipes[0][1],&str,lengthOfString); //send the actual string
主要過程:
int numberOfChar;
char* buffer;
buffer=(char*)malloc(sizeof(char)*15);
read(pipes[0][0],&numberOfChar,sizeof(int));//get length of upcoming string
read(pipes[0][0],&buffer,numberOfChar);//read the actual sting
printf("received from pipe :%s\n",buffer);
但是如果我試着與動態分配的串同樣的事情,我只收到NULL作爲字符串在主處理。這是我做的。
子過程:
char* dynamicallyAllocatedString=(char*)malloc(sizeof(char)*strlen(str));
strcpy(dynamicallyAllocatedString,str);
int lengthOfString=strlen(dynamicallyAllocatedString)+1;//+1 for null terminator
write(pipes[0][1],&lengthOfString,sizeof(int));//send the length of string beforehand
write(pipes[0][1],&dynamicallyAllocatedString,lengthOfString); //send the actual string
主要過程:
read(pipes[0][0],&numberOfChar,sizeof(int));//get length of upcoming string
buffer=(char*)malloc(sizeof(char)*numberOfChar);
read(pipes[0][0],&buffer,numberOfChar);//read the actual sting
printf("received from pipe :%s\n",buffer);
下面是完整的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc,char * argv[])
{
pid_t pid;
int numberOfPipe=1;
int ret;
int c;
int pipeNumber=-1;
int** pipes= (int**)malloc(numberOfPipe*sizeof(int));
for(c=0;c<numberOfPipe;c++)//create pipe for each process
{
pipes[c]= (int*)malloc(sizeof(int)*2);
ret = pipe(pipes[c]);
if(ret==-1)
{
perror("pipe error");
exit(1);
}
}
for(c=0;c<numberOfPipe;c++)//create child process
{
pid = fork();
pipeNumber++;
if(0==pid)
{
break;
}
}
if(0==pid)
{
// Child process
int i=0;
char* str ="from child";
char* dynamicallyAllocatedString=(char*)malloc(sizeof(char)*strlen(str));
strcpy(dynamicallyAllocatedString,str);
int lengthOfString=strlen(dynamicallyAllocatedString)+1;//+1 for null terminator
close(pipes[pipeNumber][0]); //close read side
write(pipes[pipeNumber][1],&lengthOfString,sizeof(int));//send the length of string beforehand
write(pipes[pipeNumber][1],&dynamicallyAllocatedString,lengthOfString); //send the actual string
close(pipes[pipeNumber][1]); //close write side
exit(0);
}
else
{
//main process
printf("main process\n");
int numberOfChar;
char* buffer;
for(c=0;c<numberOfPipe;c++)//close write side of each pipe
{
close(pipes[c][1]);
}
for(c=0;c<numberOfPipe;c++)//iterate each pipe
{
read(pipes[c][0],&numberOfChar,sizeof(int));//get length of upcoming string
buffer=(char*)malloc(sizeof(char)*numberOfChar);
read(pipes[c][0],&buffer,numberOfChar);//read the actual sting
printf("received from pipe :%s\n",buffer);
}
for(c=0;c<numberOfPipe;c++)//close read side of each pipe
{
close(pipes[c][0]);
}
}
printf("end");
return 0;
}
我能做些什麼來得到實際字符串而不是NULL? 謝謝。
'malloc(sizeof(char)* strlen(str))'這不足以存儲C字符串。如果你打算離開終端的'\'0',那麼一定要在兩邊適當地處理「串」。 –