Why does process child execute some unexpected line?

旧巷老猫 提交于 2019-12-02 03:22:50

问题


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...


回答1:


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.

  1. \Child will give you error in terms of "unknown escape sequence", change to \nChild.
  2. include stdlib.h for exit().
  3. include unistd.h for fork()
  4. add \n to printf("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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!