gpt4 book ai didi

c - C程序不执行main之外的函数

转载 作者:行者123 更新时间:2023-11-30 18:39:05 26 4
gpt4 key购买 nike

如果我在另一个 C 程序中执行 exec() 函数作为主函数,它会完美地工作,而如果我将它作为主菜单中调用的函数,它会给我一些警告,并且该函数不会运行。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */

int exec (void) {

char array[100];
char character;
int i = 0;
char* point;
int j = 0;

printf ("Digita una stringa");
printf ("\n");
do {
character = getchar();
array[i] = character;
i++;
}
while (character != '\n');
array[i-1] = '\0';
i = 0;

char* string[100];

char *word = strtok(array, " .");
j = 0;
while (word != NULL) {
printf("%s\n", word);
string[j++] = word; // Increment j
word = strtok(NULL, " .");
}
string[j] = NULL; // Make sure the array is NULL term

printf ("\n");

pid_t pid;
pid = fork();
int status;

if (pid == -1) {
perror("");
}else if (pid == 0) {
execvp(string[0], string); /* execute the command */
fprintf(stderr, "Failed to exec");
exit(1);
}
else {

//.. wait until the child ends
waitpid(-1, &status, 0);
}

return;
}

int read_input (void) {
int choice;
printf("Seleziona una voce dal menu");
do {
printf("\n");
scanf ("%i", &choice);
if (choice > 8 || choice < 1)
printf ("Attenzione, inserisci un valore contemplato dal menu");
}
while ( choice > 8 || choice < 1);

return choice;
}

void main (int argc, char *argv[]) {

printf ("------------------------\n");
printf (" MENU \n");
printf ("------------------------\n");
printf (" \n");
printf ("1) Esecuzione in foreground di un processo\n");
printf ("2) Ctrl -C\n");
printf ("3) Exit\n");
printf ("4) Background\n");
printf ("5) Pipe\n");
printf ("6) Jobs\n");
printf ("7) fg\n");
printf ("8) kill\n");
int menu = read_input();
switch (menu) {

case '1' :
exec ();
break;
case '2' :
//ctrl();
break;
case '3' :
//exit_();
break;
case '4' :
//background();
break;
case '5' :
//pipe();
break;
case '6' :
//jobs();
break;
case '7' :
//fg();
break;
case '8' :
//kill();
break;
}
}

这是警告:

elaborato.c:31:16: warning: initialization makes pointer from integer without a cast [enabled by default] char *word = strtok(array, " ."); 

最佳答案

关于输入相关的问题,

do {    
printf("\n");
scanf ("%i", &choice);
if (choice > 8 || choice < 1)
printf ("Attenzione, inserisci un valore contemplato dal menu");
}
while ( choice > 8 || choice < 1);

一旦输入一个整数并按 Enter 键,scanf() 就会消耗该数字,并在标准输入中留下一个换行符。下次循环进行时(假设输入 <1 或 >8 或其他内容) scanf 获取换行符并继续。在 scanf() 之后添加 getchar()

关于c - C程序不执行main之外的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31088731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com