So I'm getting to know how processes work and have written some simple code.
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int SemId;
void SemGet(int n)
{
SemId = semget(IPC_PRIVATE, n, 0600);
if (SemId == -1) {
exit(1);
}
}
int SemSetVal(int SemNum, int SemVal)
{
return semctl(SemId, SemNum, SETVAL, SemVal);
}
int SemOp(int SemNum, int SemOp)
{
struct sembuf SemBuf;
SemBuf.sem_num = SemNum;
SemBuf.sem_op = SemOp;
SemBuf.sem_flg = 0;
return semop(SemId, & SemBuf, 1);
}
void SemRemove(void)
{
(void) semctl(SemId, 0, IPC_RMID, 0);
}
void child(int vchild) {
printf("\nChild %d", vchild);
return;
}
int main(int argc, char** argv) {
printf("\nHeeeyoooo!");
if (fork() == 0) {
child(1);
exit(0);
}
(void) wait(NULL);
printf("\nParent.");
return 0;
}
and what I get for output is
Heeeyoooo!
Child 1Heeeyoooo!
Parent.
Process returned 0 (0x0) execution time : 0.001 s
Press ENTER to continue.
Why do I get "heyooo" twice? I seems like the child is getting back into the main instead of getting terminated by the exit...
child is getting back into the main instead of getting terminated by the exit
..no, that's not the case.
There are many issues with your code.
\Child
will give you error in terms of "unknown escape sequence", change to\nChild
.- include
stdlib.h
forexit()
. - include
unistd.h
forfork()
- add
\n
toprintf("Heeeyoooo!");
to flush the output buffer.
After 1,2 and 3, the main problem in your code is, there is no newline escape sequence
present in your printf()
which is why your output buffer is not flushed. So, to flush out the standard output buffer before next print, add a newline escape sequence [\n
] which will flush the buffer.
Worth of mentioning, from the man page of fork()
The child process shall have its own copy of the parent's open directory streams. Each open directory stream in the child process may share directory stream positioning with the corresponding directory stream of the parent
which means, without the flushing of the buffer, Heeeyoooo!
is still present in child's output stream and hence it is printed again.
If you write
printf("Heeeyoooo!");
fflush(stdout);
and then fork, the error goes away. The reason is that fork()
clones the output buffer for stdout while "Heeeyoooo!"
is still in it, so it is subsequently printed twice.
来源:https://stackoverflow.com/questions/27459570/why-does-process-child-execute-some-unexpected-line