子进程的主函数

Main function for a child process

本文关键字:函数 子进程      更新时间:2023-10-16

我有一个小而令人困惑的问题...第一个问题是主要的用途是什么。我知道这个问题既愚蠢又简单,但我有一个问题。我写了一个代码

#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>

int main(){
pid_t ty;
ty=fork();
if(ty==0){
const char* x="/home/brucewilson/Desktop/jack_sahoo_teja_CDP/hey2";
static char *argv[]={"echo","Foo is my name.",NULL};
int main(){//observe this is second main in my child process
printf("hello");
}
int add(){
printf("5");
}
main();
add();
}

}'

您是否很好地观察了我在子进程中使用的第二个主要函数,编译器没有给我任何错误。.除此之外,它还给了我"hello"和 5 的输出。

显然,下面的代码会给出一个错误...

int main(){
printf("main");
main();
}
int main(){
}

所以我的问题是为什么它对子进程有效?因此,假设 im 为真,没有函数可以命名为 main(),并且每个子进程都有一个与其父进程共享的主函数的概念是错误的。请解释一下我的系统内这段代码下面发生了什么,因为子进程将 main 作为另一个函数,它也不需要 main 函数。那么子进程如何知道它应该从哪里开始呢?

您正在使用称为"嵌套函数"的非标准 GCC 扩展。

第二个示例失败,因为您没有嵌套main()的第二个定义,因此它与第一个定义冲突。