This is what my code looks like:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
char* reverseString(char*);
int main(void)
{
pid_t id;
int fd[2], nbytes;
char string[80];
char readbuffer[80];
char* reversed;
pipe(fd);
if((id = fork()) == -1)
{
perror("fork");
exit(1);
}
if(id != 0)
{
close(fd[0]);
printf("PARENT\n--------------------\n");
// printf("fork: %d\n", id);
printf("my pid is %d\n", getpid());
// printf("my parent's pid is %d\n", getppid());
printf("enter string: ");
scanf("%s", string);
write(fd[1], string, (strlen(string)+1));
}
else
{
close(fd[1]);
printf("CHILD\n--------------------\n");
// printf("fork: %d\n", id);
printf("my pid is %d\n", getpid());
// printf("my parent's pid is %d\n", getppid());
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s\n", readbuffer);
reversed = reverseString(readbuffer);
printf("Reversed string: %s\n", reversed);
pid_t id2;
int fd2[2];
char readbuffer2[80];
pipe(fd2);
if((id2 = fork()) != 0)
{
close(fd2[0]);
printf("My pid: %d\n", getpid());
write(fd2[1], reversed, (strlen(reversed)+1));
}
else
{
close(fd2[1]);
printf("My Child's PID: %d\n", getpid());
nbytes = read(fd2[0], readbuffer2, sizeof(readbuffer2));
printf("Received string2: %s\n", readbuffer2);
}
}
return (0);
}
char* reverseString(char* str)
{
char reversed[80];
int n = strlen(str);
for(int i = n - 1, j = 0; i >= 0; i--, j++)
reversed[j] = str[i];
reversed[n] = '\0';
return reversed;
}
I'm trying to pipe the reversed string into the third process forked in the second process, but it is not showing up.
Also, when I do scanf
after enter, the printing keeps going until the child part is printed, then I enter the string. How do I keep it from printing everything. It looks like this:
PARENT
--------------------
my pid is 821
enter string: CHILD
--------------------
my pid is 822
$
In reverseString
function you are returning the array address which is an automatic local variable. Such variables gets destroyed when the function returns.
char* reverseString(char* str)
{
char reversed[80];
// local array, cannot use it after the function returns
Either use malloc()
to allocate memory which will be preserved in between function calls, or reverse the string inplace.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments