为什么孩子过程中执行一些意想不到的线? [英] Why does process child execute some unexpected line?

查看:107
本文介绍了为什么孩子过程中执行一些意想不到的线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我结识的过程是如何工作的,并写了一些简单的code。

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;
}

和我所得到的输出

Heeeyoooo!
Child 1Heeeyoooo!
Parent.
Process returned 0 (0x0)   execution time : 0.001 s
Press ENTER to continue.

为什么我得到heyooo两次?
我好像孩子正在恢复到主而不是由出口遭到停...

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.

有您的code许多问题。

There are many issues with your code.


  1. \\儿童会给你错误的未知转义序列条款,更改为 \\ nChild

  2. 包含文件stdlib.h 退出()

  3. 包含 unistd.h中叉()

  4. 添加 \\ n 的printf(Heeeyoooo!); 来刷新输出缓冲区

  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.

1,2,3,之后的主要的在code的问题是,有没有换行转义序列 present在你的的printf()这就是为什么你的输出缓冲区不会刷新。因此,冲洗出来下一个打印前的标准输出缓冲区,增加一个换行符转义序列[ \\ n ]这将刷新缓冲区。

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

,这意味着,如果没有缓冲的潮红, Heeeyoooo!仍present在孩子的输出流并因此它被再次打印。

which means, without the flushing of the buffer, Heeeyoooo! is still present in child's output stream and hence it is printed again.

这篇关于为什么孩子过程中执行一些意想不到的线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆