views:

153

answers:

2
+2  Q: 

Fork() on iPhone

Does the the iPhone SDK allow fork() and pipe(), the traditional unix functions? I can't seem to make them working.

Edit

Problem solved. Here, I offer a solution to anybody who encounters problems similar to me. I was inspiried by the answers in this thread.

In iPhone, there is no way to fork a process. However, it's not impossible to implement pipling. 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.

+4  A: 

Nope. You also can't exec. You have 1 process.

cobbal
+5  A: 

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?

Kendall Helmstetter Gelner
You are right. I was trying to use fork() because it was the standard practice in UNIX. Also, if we printf() in a different process, it wouldn't affect the child process. iPhone doesn't allow this, so I decided to switching to multiple threads.
Kinderchocolate