我有这段代码:
int main ()
{
int pid, fd[2], i, j;
char comanda[1000], comm[100][100], *var, *var2, vect[100][100], check[10000];
if(pipe(fd)<0) // nu creaza pipe-ul
{
perror("pipe error");
exit(1);
}
if((pid = fork()) < 0 ) //nu face fork
{
perror("fork error");
exit(1);
}
j = 0;
if(pid){
do {
if( j > 0) fgets (check , 1000 , stdin);
printf("enter command: \n");
scanf("%[^\t\n]", comanda);
if(var = strtok(comanda, " "))
{
i=0;
while(var != NULL)
{
strcpy(vect[i], var);
var = strtok(NULL, " ");
i++;
}
}
else
strcpy(vect[0], comanda);
if(strcmp(vect[0], "login") == 0)
{
write(fd[1], "login ", 6);
write(fd[1], vect[1], strlen(vect[1]));
printf("Sending the child %s \n", vect[1]);
}
else if(strcmp(vect[0], "quit") == 0)
{
exit(1);
}
else
printf("I got the command %s \n", vect[0]);
j++;
} while(1);
close(fd[0]);
close(fd[1]);
wait(NULL);
}
else
{
do
{
char text[1000];
close(fd[1]);
int i=0;
strcpy(text, "");
read(fd[0], text, sizeof(text));
printf("I've read %s \n", text);
var2 = strtok(text, " ");
j=0;
while(var2 != NULL)
{
strcpy(comm[j], var2);
var2 = strtok(NULL, " ");
j++;
}
if( strcmp(comm[0], "login") == 0)
{
printf("comm[1] e %d \n", comm[1]);
if(login(comm[1]))
{
printf("OKK! \n");
}
else
{
printf("Username not in /etc/passwd \n");
}
}
//close(fd[0]);
} while(1);
}
return 0;
}
现在问题是...在父进程中它读取命令...如果我给他登录adam.johnson ...它将adam.johnson罚款给约翰逊他在哪里工作......现在,当它回到父进程时,如果我再次给他登录wa ,它将从父进程读取为登录waam .johnson (保持am.johnson不受adam.johnson的伤害!
答案 0 :(得分:0)
在子节点中,您没有使用调用read
(读取的字节数)的返回值,也没有使用父节点发送结束字符串的nul char。因此,当您发送比最后一个更短的字符串时,您正在重复使用缓冲区的部分缓冲区。
您可以尝试在父级中发送nul char:
write(fd[1], "login ", 6);
write(fd[1], vect[1], strlen(vect[1]) +1);