c-在fork中调用一个函数,函数中有一个while循环,它应该读取输入,但是,scanf()被完全跳过



这里是main()分叉并调用函数的位置:

#include <fcntl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>

#include"sp-pipe-client.h"
pid_t clientChild, serverChild, c1 child1Stat;
int main() {
if ((serverChild = fork()) == 0) {
}
else if ((clientChild = fork()) == 0) {
SP_Pipe_Client();
}
else {
c1 = wait(&child1Stat);
} 
}

标题:


void SP_Pipe_Client();

这是一个函数,其中scanf被完全跳过,而循环无限打印菜单:


#include <fcntl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
char input = 'a', fileName[50];
int puzzleSize = 4;
int tile;
void SP_Pipe_Client() {
while (input != 'q') {
//  if (IsGameWon(puzzleSize, slidingPuzzle)) {
//      printf("Congratulations, you have won the game!n");
//  }
printf("Menu: [p]rint, [m]ove, [n]ew, [s]ave, [l]oad, [q]uit?n");
scanf(" %c", &input);
if (input == 'p') {
//DisplayBoard(puzzleSize, slidingPuzzle);
}
else if (input == 'm') {
printf("Enter tile # to move: ");
scanf(" %d", &tile);
//MovePiece(tile, puzzleSize, slidingPuzzle, rowP, colP);
}
else if (input == 'n') {
printf("Enter a size for new game (2-10): ");
scanf(" %d", &puzzleSize);
while (puzzleSize < 2 || puzzleSize > 10) {
printf("Enter a valid size for new game (2-10): ");
scanf(" %d", &puzzleSize);
}
//free(slidingPuzzle);
//slidingPuzzle = Initialize(puzzleSize);
}
else if(input == 's'){
printf("Please enter file name for saving. (max 30 characters including '.txt'n");
scanf("%s", fileName);
//SaveGame(puzzleSize, slidingPuzzle, fileName);
}
else if(input == 'l'){
printf("Please enter file name for saving. (max 30 characters including '.txt'n");
scanf("%s", fileName);
//slidingPuzzle = LoadGame(size, fileName, slidingPuzzle);
}
else if(input == 'q') {
//TearDown(slidingPuzzle);
exit(0);
}
else {
printf("Invalid input, try againn");
}
}
}

主函数应该调用这个函数和一个我还没有编码的服务器函数,这些函数在它们自己的.c文件中。当分叉时,子级调用函数并无限打印底部的菜单和else语句。

我已经尝试过改变"%c"的哪一边吃掉n,以及将其提供给两边并使用它本身,我也尝试过fgetc()吃掉新行并获得输入本身,但无论循环保持无限,scanf()fgetc()都不会发生。

编辑:我也尝试过移动我的变量声明,它们曾经在子调用的函数中,也没有什么不同。

我已经想通了。问题是,我只调用了wait((一次,但我创建了两个子进程,所以我的main只等待一个子进程死亡,因为我还没有为我的服务器子进程编写代码,所以它正在结束,所以主进程正在结束,让客户端子进程作为孤儿继续自己的工作,不接受任何输入。我通过添加";c2=等待(&child2Stat("到else语句,允许我的主进程同时等待客户端和服务器子进程:

int main(){
pipe(pipe_command);
pipe(pipe_param_result);
if((serverChild = fork()) == 0){
}
else if((clientChild = fork()) == 0){
SP_Pipe_Client();
}
else{
c1 = wait(&child1Stat);
c2 = wait(&child2Stat);
}

}

相关内容

最新更新