[英]Calling a function within a fork, within the function is a while loop which should be reading input, however, scanf() is completely skipped
這里是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 文件中。 當 fork 時,子進程調用該函數並在底部無限地打印菜單和 else 語句。
我已經嘗試改變"%c"
哪一邊吃\\n
,以及把它給兩邊並使用 \\n 本身,我也試過fgetc()
既吃新行又得到輸入本身但是無論循環如何保持無限, scanf()
和fgetc()
不會發生。
編輯:我也試過移動我的變量聲明,它們曾經在孩子調用的函數內,也沒有區別。
我已經想通了。 問題是我只調用了 wait() 一次,但是我創建了兩個子進程,所以我的主進程只等待一個子進程死亡,這是因為我還沒有為我的服務器子進程編寫代碼,所以我的主進程即將結束,讓客戶孩子作為孤兒繼續自己,不接受任何輸入。 我通過添加“c2 = wait(&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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.