下面是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 again\n");
}
}
}main函数应该调用这个函数和一个服务器函数,这些函数都在它们自己的.c文件中。在派生时,子代调用函数并无限地打印菜单和底部的else语句。
我已经尝试更改"%c"的哪一端吃掉\n,以及将其提供给两端并使用\n本身,我还尝试了fgetc()来吃掉新行和获取输入本身,但无论是什么循环仍然是无限的,scanf()和fgetc()都不会发生。
编辑:我也试着移动我的变量声明,它们过去是在孩子调用的函数中,也没有什么不同。
发布于 2021-11-09 17:07:07
我已经弄明白了。问题是我只调用了wait()一次,但我创建了两个子进程,所以我的main只等待一个子进程死亡,因为我还没有为我的服务器子进程编写代码,所以它结束了,所以我的主进程结束了,让客户端子进程作为一个孤立进程继续运行,不接受任何输入。我通过向else语句添加"c2 = wait (&children 2STAT);“来修复这个问题,允许我的主进程同时等待客户端和服务器的子进程:
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);
}
}https://stackoverflow.com/questions/69891593
复制相似问题