Fork() on iPhone
Does the the iPhone SDK allow fork()
and pipe()
, the traditional unix functions? I can't seem to make them work.
Edit
Problem solved. Here, I offer a solution to anybody who encounters problems similar to me. I was inspired by the answers in this thread.
In iPhone, there is no way to fork a process. However, it's not impossible to implement piping. In my project, I create a new POSIX thread (read Apple's documentation for how to do this). The child thread would share a file descriptor created by pipe() with the parent thread. Child and parent threads can communicate via pipes. For example, my child thread dup2() fd[1] to its standard output. So any standard output could be 开发者_如何学运维caught in the parent thread. Similar to fd[0] and standard input.
Pseudocode (I don't have the code available but you get the idea):
int fd[2];
pipe(fd);
create_posix_thread(&myThread, fd);
char buffer[1024];
read(fd[0], buffer, 1024);
printf("%s", buffer); // == "Hello World"
void myThread(int fd[])
{
dup2(fd[1], STANDARD_OUTPUT);
printf("Hello World");
}
The strategy is very handy if you want to use a third-party library within your iPhone application. However, a problem is that standard debug using printf() is no longer available. In my project, I simply directed all debug outputs to standard error, XCode would display the outputs to its console.
You can't fork() but you can use as many threads as you like, and now you even have GCD on the iPhone to help keep thread use reasonable.
Why do you want to fork() instead of just using more threads?
Nope. You also can't exec. You have 1 process.
精彩评论