{"id":1395,"date":"2015-07-04T00:01:16","date_gmt":"2015-07-04T07:01:16","guid":{"rendered":"http:\/\/c-for-dummies.com\/blog\/?p=1395"},"modified":"2015-06-27T08:13:44","modified_gmt":"2015-06-27T15:13:44","slug":"a-fork-in-your-code","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=1395","title":{"rendered":"A Fork in Your Code"},"content":{"rendered":"<p>All of the code I&#8217;ve written in my books as well as demonstrated on this blog has been single-tasking: The program runs as one process, does one thing, in order, and then terminates. With this Lesson, that streak ends.<br \/>\n<!--more--><br \/>\nToday&#8217;s operating systems handle multiple programs at once. They&#8217;re not called programs, but rather <em>processes<\/em>. So when you start some silly little C program you&#8217;ve written, it&#8217;s spawned as a new process in the system. The process is assigned a number or process ID (PID). It starts, runs, then stops. All the while other processes continue to run.<\/p>\n<p>Spawning a new process inside a single program is the duty of the <em>fork()<\/em> function. That function is declared in the <code>unistd.h<\/code> header file. It returns a PID value representing a duplicate copy of the existing program call the <em>child<\/em>. The original code is called the <em>parent<\/em>.<\/p>\n<p>When using the <em>fork()<\/em> function, it&#8217;s important to remember that the parent code is spawned as the child. So unlike the <em>system()<\/em> function, <em>fork()<\/em> doesn&#8217;t launch another program. Instead, you keep track of the two copies of the current code by using PID values.<\/p>\n<p>Time for an example!<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;unistd.h&gt;\r\n\r\nint main()\r\n{\r\n    fork();\r\n    printf(\"This code's PID is %d\\n\",getpid());\r\n\r\n    return(0);\r\n}<\/pre>\n<p>Here&#8217;s sample output:<\/p>\n<pre><code>This code's PID is 59918\r\nThis code's PID is 59919<\/code><\/pre>\n<p>Despite only one <em>printf()<\/em> statement in the code, two lines are output. That&#8217;s because the <em>fork()<\/em> function spawned a child program, which ran its own <em>printf()<\/em> statement. The <em>fork()<\/em> function&#8217;s success is evident because the output shows two process ID values, parent and child. (Refer to <a href=\"http:\/\/c-for-dummies.com\/blog\/?p=1428\">last week&#8217;s Lesson<\/a> for info on the <em>getpid()<\/em> function.)<\/p>\n<p>Tracking PID values can be bothersome, so the <em>fork()<\/em> function assists you by returning different values, one for the parent process and another for the child. The parent process receives the value zero from the <em>fork()<\/em> function. The child process receives the parent&#8217;s process ID. You use these values to determine which process is running in your code.<\/p>\n<p>Time for another example:<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;unistd.h&gt;\r\n\r\nint main()\r\n{\r\n    pid_t pid;\r\n\r\n    pid = fork();\r\n\r\n    switch(pid)\r\n    {\r\n        case 0:\r\n            printf(\"Parent PID: %d\\n\",getpid());\r\n            printf(\"Parent fork() return value: %d\\n\",pid);\r\n            break;\r\n        default:\r\n            printf(\"Child PID: %d\\n\",getpid());\r\n            printf(\"Child fork() return value: %d\\n\",pid);\r\n    }\r\n\r\n    return(0);\r\n}<\/pre>\n<p>Here&#8217;s the output on my machine:<\/p>\n<pre><code>Child PID: 59986\r\nChild fork() return value: 59987\r\nParent PID: 59987\r\nParent fork() return value: 0<\/code><\/pre>\n<p>In the parent copy of the program, <em>fork()<\/em> returns 0. The parent&#8217;s PID is 59987.<\/p>\n<p>The child copy receives the parent&#8217;s PID from the <em>fork()<\/em> function, 59987, but it has its own PID value, which is 59986, as shown above.<\/p>\n<blockquote><p>The order of output for the Child and Parent is unpredictable, given that you&#8217;re witnessing two programs running and both are using streamed output.<\/p><\/blockquote>\n<p>Once your code determines whether the child or parent is running, it can separate statements and functions to carry out multitasking. So the child part may dash off and run some function while the parent copy of the code does something else. Both processes happen simultaneously.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>One program that&#8217;s two programs at once. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=1395\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-1395","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1395","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1395"}],"version-history":[{"count":6,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1395\/revisions"}],"predecessor-version":[{"id":1445,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1395\/revisions\/1445"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1395"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1395"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1395"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}