我实现了一个系统调用宏来调用软件中断。对于许多系统调用,这都很有效。然而,对于 fork()
一点也不行。父进程和子进程的返回 pid 是相同的。代码片段如下:
#define SYSCALL0(N) ({ \
register int ip asm("ip") = N; \
register int r0 asm("r0"); \
asm volatile("swi 0x80" : "=r"(r0) : "r"(ip) : "memory"); \
r0; \
})
int main(int argc, char * argv[]) {
NSLog(@"--beginning of program\n");
int counter = 0;
pid_t pid = SYSCALL0(2);
if (pid == 0) {
NSLog(@"pid = %d", getpid());
// child process
for (int i = 0; i < 3; ++i)
NSLog(@"child process: counter=%d\n", ++counter);
}
else if (pid > 0) {
NSLog(@"pid = %d", getpid());
// parent process
for (int i = 0; i < 3; ++i)
NSLog(@"parent process: counter=%d\n", ++counter);
}
else {
// fork failed
NSLog(@"fork() failed!\n");
return 1;
}
NSLog(@"--end of program--\n");
}
输出:
2015-10-11 21:29:43.666 Training[2564:907] --beginning of program
2015-10-11 21:29:43.669 Training[2564:907] pid = 2650
2015-10-11 21:29:43.670 Training[2564:907] parent process: counter=1
2015-10-11 21:29:43.670 Training[2564:907] parent process: counter=2
2015-10-11 21:29:43.669 Training[2564:907] pid = 2650
2015-10-11 21:29:43.671 Training[2564:907] parent process: counter=3
2015-10-11 21:29:43.671 Training[2564:907] --end of program--
2015-10-11 21:29:43.671 Training[2564:907] parent process: counter=1
2015-10-11 21:29:43.672 Training[2564:907] parent process: counter=2
2015-10-11 21:29:43.673 Training[2564:907] parent process: counter=3
2015-10-11 21:29:43.674 Training[2564:907] --end of program--
被测试的环境是一个越狱的 iOS 系统(非越狱系统无法运行),运行在 armv7 处理器上。我认为可能没有对 swi 调用的返回值做足够的处理,因此无法返回 0 来指示子进程。我错过了什么?如何使其正常工作?