GCC编译遇到“a label can only be part of a statement and a declaration is not a statement”问题

  • 问题原因:switch中case里面的局部变量出错
  • 解决方法:将case里面定义的局部变量在switch外面定义。
//报错情况
        switch (fork()) {
        case -1:
            error(1, errno, "fork");
        case 0:
            // 子进程执行命令
            if (execvp(args[0], args) == -1) { 
                error(1, errno, "execvp");
            }
        default:
            // 父进程等待子进程结束
            int wstatus;
            pid_t pid = wait(&wstatus);
            printf("\n%d terminated. ", pid);
            print_wstatus(wstatus);
        }
//解决方案
int wstatus;
        pid_t pid;
        switch(fork()){
        case -1:
            error(1,errno,"fork");

        case 0:
            if(execvp(args[0],args) == -1){
                error(1,errno,"execvp");
            }
           // exit(1);
        default:

            pid = wait(&wstatus);
            if(pid > 0){
                printf("\nchildpid:%d ",pid);
                print_wstatus(wstatus);
            }
         }
posted @ 2024-05-25 10:36  Uiney  阅读(22)  评论(0编辑  收藏  举报