I'm new to programming, and I made code that does the following:
- create a pointer address in a
fork()
parent process that points to "int 2". - The parent process converts the pointer address to a
long int
, and then a string. - The parent process writes the string into a pipe.
wait(NULL);
forces the parent process to wait for the child process to exit.- the child process proceeds to read the address into an empty string.
- the child process converts the string back into a
long int
, then into a pointer address. - the child process attempts to print the value that the address points to "int 2".
- the child process exits.
- the parent process resumes and converts the string back into a
long int
, which then gets converted back into a pointer address. - the parent process attempts to print the value that the address points to "int 2"
The result is that the parent process receives the address that was converted from a string, and successfully prints "2". The child process receives exactly the same address before the parent process does, but the address contains junk because it prints "0". printf
commands were peppered throughout to ensure that the original address remained intact throughout the process.
The following is the relevant code. The output is placed after the code. Note that WAIT(400)
is just a loop that makes the child process wait for the parent process to finish writing the address into the pipe. I defined it elsewhere, and it doesn't interact with any of the other functions.
int main(void) {
int s[2];
pipe(s);
int pid;
long nbytes;
char buffer[80];
pid = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) {
close(s[1]);
WAIT(200);
nbytes = read(s[0], buffer, sizeof(buffer));
printf("%s\n", buffer);
int *q = stringToAdress(buffer);
printf("%ld\n", q);
printf("%d\n", *q);
} else {
close(s[0]);
int *p = malloc(sizeof(int));
*p = 2;
printf("%ld\n", p);
char *str = addressToString(p);
printf("%s\n", str);
write(s[1], str, (strlen(str) + 1));
wait(NULL);
int *q = stringToAdress(str);
printf("%ld\n", q);
printf("%d\n", *q);
free(p);
exit(EXIT_SUCCESS);
}
}
The following is the output. I believe that everything is expected except for the 0
. I don't know why it's not a 2
.
4301258912
4301258912
4301258912
4301258912
0
4301258912
2
Program ended with exit code: 0