linux - In C programming language, how can variable store two values? -
this question has answer here:
- how possible fork() return 2 values? 5 answers
i've decided learn c, , here snippet 1 of books use:
#include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { pid_t result = fork(); if (result == -1){ fprintf(stderr, "error\n"); return 1; } if (result == 0) printf("i'm child pid = %d\n", getpid()); else printf("i'm parent pid = %d\n", getpid()); return 0; }
its output is:
i'm parent pid = 5228 i'm child pid = 5229
everything's clear, how result == 0
, result != 0
@ same time? looks variable stores 2 values, because printf
instruction executed twice. know, fork()
returns 0
, parent's pid, how result
check if returns true different conditions?
because it's not same variable. when fork
process, end 2 totally different processes (see this answer more detail).
hence result
variable in parent not same 1 in child. you're seeing two processes, both attached same output device, each writing own message.
in fact, fork
documentation covers that:
on success, pid of child process returned in parent, , 0 returned in child.
so can use return value fork
(as do) see if you're parent or child (and see if worked well, it'll return -1
if fails , you'll parent no child).
the idea parent gets process id of child can (like wait()
finish) , child gets zero. child can process id of parent calling getppid()
.
Comments
Post a Comment