File Operations and Processes












1















Is it possible that two different processes(parent and child) can see the same text file and manipulate it ?



I accomplished this, but I had to open the file in both processes by using fopen(). My expectation is that one of the processes opens the file and the other one can see and manipulate it.










share|improve this question



























    1















    Is it possible that two different processes(parent and child) can see the same text file and manipulate it ?



    I accomplished this, but I had to open the file in both processes by using fopen(). My expectation is that one of the processes opens the file and the other one can see and manipulate it.










    share|improve this question

























      1












      1








      1








      Is it possible that two different processes(parent and child) can see the same text file and manipulate it ?



      I accomplished this, but I had to open the file in both processes by using fopen(). My expectation is that one of the processes opens the file and the other one can see and manipulate it.










      share|improve this question














      Is it possible that two different processes(parent and child) can see the same text file and manipulate it ?



      I accomplished this, but I had to open the file in both processes by using fopen(). My expectation is that one of the processes opens the file and the other one can see and manipulate it.







      files process c






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 4 '18 at 11:14









      GoktugGoktug

      2519




      2519






















          2 Answers
          2






          active

          oldest

          votes


















          1














          From the fork(2) manual on my OpenBSD system (my emphasis):




          The child process has its own copy of the parent's descriptors.
          These descriptors reference the same underlying objects, so
          that, for instance, file pointers in file objects are shared
          between the child and the parent
          , so that an lseek(2) on a
          descriptor in the child process can affect a subsequent read(2)
          or write(2) by the parent. This descriptor copying is also
          used by the shell to establish standard input and output for
          newly created processes as well as to set up pipes.




          This means that if you open a file in the parent process before forking the child, both processes will have the same file opened. However, if the child reads from the file, then the parent's file pointer will also be moved.



          To access a file in both processes independently, you have to open the file in both processes separately.



          If you open a file in the parent after the call to fork(), it will not be opened in the child process, and vice versa.






          share|improve this answer
























          • Everything is okay for me. There is only one thing that I wonder. Parent process opened the file. After that, child process is forked. In this case, how can child process access the file pointer ? What I mean is whether the file pointer is sent to child process via the parameter argv ?

            – Goktug
            Mar 4 '18 at 11:28











          • @Goktug The child process is an exact copy of the parent. You should be able to just use the file pointer. It was inherited from the parent.

            – Kusalananda
            Mar 4 '18 at 11:37











          • You are right. Actually, I could not image it and I forgot that they were inherited from parent process to child process.

            – Goktug
            Mar 4 '18 at 11:46











          • I wrote a code in which the child process try to read a file opened by its parent process previously. Actually, the operating system does not let the child process read the file. There is a while loop in both parent and child process to read the file. At first, parent process read some contents of the file. Then, child process is executed and child process's ID is printed. When the execution comes to the while loop which reads the file in child process, operating system continue to execute parent process. In other words, it never executes the while loop in child process.

            – Goktug
            Mar 5 '18 at 17:54













          • @Goktug Since file pointers are shared between parent and child, and if the parent had already reached end-of-file, then any attempt to read from the same file pointer in the child would return end-of-file immediately.

            – Kusalananda
            Mar 5 '18 at 17:56



















          0














          And here is some example code that does just that.



          #include <err.h>
          #include <stdio.h>
          #include <unistd.h>

          char buf[8];

          int main(int argc, char *argv)
          {
          int ch, fd[2], rv;

          pipe(fd);

          switch (fork()) {
          case -1:
          err(1, "could not fork");
          case 0: // child
          rv = lseek(STDIN_FILENO, -7, SEEK_END);
          if (rv == -1) err(1, "could not seek");
          sleep(3);
          close(fd[1]);
          break;
          default: // parent
          close(fd[1]);
          read(fd[0], &ch, 1);
          read(STDIN_FILENO, buf, 7);
          printf("read '%s'n", buf);
          }
          return 0;
          }


          what is going on is that the parent blocks waiting for the child and meanwhile the child seeks to the end of standard input, minus seven, then closes the pipe(2) to the parent. This unblocks the parent, which reads from the shared descriptor from where the child moved the shared file pointer to.



          $ make sharedseek
          cc sharedseek.c -o sharedseek
          $ echo asdfasdfasdf123456 > x
          $ ./sharedseek < x
          read '123456
          '
          $


          This will not work if standard input is not seekable. Also the pipe (or some form of communication) is really necessary as otherwise the parent may run before the child.



          If the file descriptor was not shared then the parent would not read from where the child moved the pointer to.






          share|improve this answer

























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "106"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f428043%2ffile-operations-and-processes%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            From the fork(2) manual on my OpenBSD system (my emphasis):




            The child process has its own copy of the parent's descriptors.
            These descriptors reference the same underlying objects, so
            that, for instance, file pointers in file objects are shared
            between the child and the parent
            , so that an lseek(2) on a
            descriptor in the child process can affect a subsequent read(2)
            or write(2) by the parent. This descriptor copying is also
            used by the shell to establish standard input and output for
            newly created processes as well as to set up pipes.




            This means that if you open a file in the parent process before forking the child, both processes will have the same file opened. However, if the child reads from the file, then the parent's file pointer will also be moved.



            To access a file in both processes independently, you have to open the file in both processes separately.



            If you open a file in the parent after the call to fork(), it will not be opened in the child process, and vice versa.






            share|improve this answer
























            • Everything is okay for me. There is only one thing that I wonder. Parent process opened the file. After that, child process is forked. In this case, how can child process access the file pointer ? What I mean is whether the file pointer is sent to child process via the parameter argv ?

              – Goktug
              Mar 4 '18 at 11:28











            • @Goktug The child process is an exact copy of the parent. You should be able to just use the file pointer. It was inherited from the parent.

              – Kusalananda
              Mar 4 '18 at 11:37











            • You are right. Actually, I could not image it and I forgot that they were inherited from parent process to child process.

              – Goktug
              Mar 4 '18 at 11:46











            • I wrote a code in which the child process try to read a file opened by its parent process previously. Actually, the operating system does not let the child process read the file. There is a while loop in both parent and child process to read the file. At first, parent process read some contents of the file. Then, child process is executed and child process's ID is printed. When the execution comes to the while loop which reads the file in child process, operating system continue to execute parent process. In other words, it never executes the while loop in child process.

              – Goktug
              Mar 5 '18 at 17:54













            • @Goktug Since file pointers are shared between parent and child, and if the parent had already reached end-of-file, then any attempt to read from the same file pointer in the child would return end-of-file immediately.

              – Kusalananda
              Mar 5 '18 at 17:56
















            1














            From the fork(2) manual on my OpenBSD system (my emphasis):




            The child process has its own copy of the parent's descriptors.
            These descriptors reference the same underlying objects, so
            that, for instance, file pointers in file objects are shared
            between the child and the parent
            , so that an lseek(2) on a
            descriptor in the child process can affect a subsequent read(2)
            or write(2) by the parent. This descriptor copying is also
            used by the shell to establish standard input and output for
            newly created processes as well as to set up pipes.




            This means that if you open a file in the parent process before forking the child, both processes will have the same file opened. However, if the child reads from the file, then the parent's file pointer will also be moved.



            To access a file in both processes independently, you have to open the file in both processes separately.



            If you open a file in the parent after the call to fork(), it will not be opened in the child process, and vice versa.






            share|improve this answer
























            • Everything is okay for me. There is only one thing that I wonder. Parent process opened the file. After that, child process is forked. In this case, how can child process access the file pointer ? What I mean is whether the file pointer is sent to child process via the parameter argv ?

              – Goktug
              Mar 4 '18 at 11:28











            • @Goktug The child process is an exact copy of the parent. You should be able to just use the file pointer. It was inherited from the parent.

              – Kusalananda
              Mar 4 '18 at 11:37











            • You are right. Actually, I could not image it and I forgot that they were inherited from parent process to child process.

              – Goktug
              Mar 4 '18 at 11:46











            • I wrote a code in which the child process try to read a file opened by its parent process previously. Actually, the operating system does not let the child process read the file. There is a while loop in both parent and child process to read the file. At first, parent process read some contents of the file. Then, child process is executed and child process's ID is printed. When the execution comes to the while loop which reads the file in child process, operating system continue to execute parent process. In other words, it never executes the while loop in child process.

              – Goktug
              Mar 5 '18 at 17:54













            • @Goktug Since file pointers are shared between parent and child, and if the parent had already reached end-of-file, then any attempt to read from the same file pointer in the child would return end-of-file immediately.

              – Kusalananda
              Mar 5 '18 at 17:56














            1












            1








            1







            From the fork(2) manual on my OpenBSD system (my emphasis):




            The child process has its own copy of the parent's descriptors.
            These descriptors reference the same underlying objects, so
            that, for instance, file pointers in file objects are shared
            between the child and the parent
            , so that an lseek(2) on a
            descriptor in the child process can affect a subsequent read(2)
            or write(2) by the parent. This descriptor copying is also
            used by the shell to establish standard input and output for
            newly created processes as well as to set up pipes.




            This means that if you open a file in the parent process before forking the child, both processes will have the same file opened. However, if the child reads from the file, then the parent's file pointer will also be moved.



            To access a file in both processes independently, you have to open the file in both processes separately.



            If you open a file in the parent after the call to fork(), it will not be opened in the child process, and vice versa.






            share|improve this answer













            From the fork(2) manual on my OpenBSD system (my emphasis):




            The child process has its own copy of the parent's descriptors.
            These descriptors reference the same underlying objects, so
            that, for instance, file pointers in file objects are shared
            between the child and the parent
            , so that an lseek(2) on a
            descriptor in the child process can affect a subsequent read(2)
            or write(2) by the parent. This descriptor copying is also
            used by the shell to establish standard input and output for
            newly created processes as well as to set up pipes.




            This means that if you open a file in the parent process before forking the child, both processes will have the same file opened. However, if the child reads from the file, then the parent's file pointer will also be moved.



            To access a file in both processes independently, you have to open the file in both processes separately.



            If you open a file in the parent after the call to fork(), it will not be opened in the child process, and vice versa.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 4 '18 at 11:20









            KusalanandaKusalananda

            125k16236389




            125k16236389













            • Everything is okay for me. There is only one thing that I wonder. Parent process opened the file. After that, child process is forked. In this case, how can child process access the file pointer ? What I mean is whether the file pointer is sent to child process via the parameter argv ?

              – Goktug
              Mar 4 '18 at 11:28











            • @Goktug The child process is an exact copy of the parent. You should be able to just use the file pointer. It was inherited from the parent.

              – Kusalananda
              Mar 4 '18 at 11:37











            • You are right. Actually, I could not image it and I forgot that they were inherited from parent process to child process.

              – Goktug
              Mar 4 '18 at 11:46











            • I wrote a code in which the child process try to read a file opened by its parent process previously. Actually, the operating system does not let the child process read the file. There is a while loop in both parent and child process to read the file. At first, parent process read some contents of the file. Then, child process is executed and child process's ID is printed. When the execution comes to the while loop which reads the file in child process, operating system continue to execute parent process. In other words, it never executes the while loop in child process.

              – Goktug
              Mar 5 '18 at 17:54













            • @Goktug Since file pointers are shared between parent and child, and if the parent had already reached end-of-file, then any attempt to read from the same file pointer in the child would return end-of-file immediately.

              – Kusalananda
              Mar 5 '18 at 17:56



















            • Everything is okay for me. There is only one thing that I wonder. Parent process opened the file. After that, child process is forked. In this case, how can child process access the file pointer ? What I mean is whether the file pointer is sent to child process via the parameter argv ?

              – Goktug
              Mar 4 '18 at 11:28











            • @Goktug The child process is an exact copy of the parent. You should be able to just use the file pointer. It was inherited from the parent.

              – Kusalananda
              Mar 4 '18 at 11:37











            • You are right. Actually, I could not image it and I forgot that they were inherited from parent process to child process.

              – Goktug
              Mar 4 '18 at 11:46











            • I wrote a code in which the child process try to read a file opened by its parent process previously. Actually, the operating system does not let the child process read the file. There is a while loop in both parent and child process to read the file. At first, parent process read some contents of the file. Then, child process is executed and child process's ID is printed. When the execution comes to the while loop which reads the file in child process, operating system continue to execute parent process. In other words, it never executes the while loop in child process.

              – Goktug
              Mar 5 '18 at 17:54













            • @Goktug Since file pointers are shared between parent and child, and if the parent had already reached end-of-file, then any attempt to read from the same file pointer in the child would return end-of-file immediately.

              – Kusalananda
              Mar 5 '18 at 17:56

















            Everything is okay for me. There is only one thing that I wonder. Parent process opened the file. After that, child process is forked. In this case, how can child process access the file pointer ? What I mean is whether the file pointer is sent to child process via the parameter argv ?

            – Goktug
            Mar 4 '18 at 11:28





            Everything is okay for me. There is only one thing that I wonder. Parent process opened the file. After that, child process is forked. In this case, how can child process access the file pointer ? What I mean is whether the file pointer is sent to child process via the parameter argv ?

            – Goktug
            Mar 4 '18 at 11:28













            @Goktug The child process is an exact copy of the parent. You should be able to just use the file pointer. It was inherited from the parent.

            – Kusalananda
            Mar 4 '18 at 11:37





            @Goktug The child process is an exact copy of the parent. You should be able to just use the file pointer. It was inherited from the parent.

            – Kusalananda
            Mar 4 '18 at 11:37













            You are right. Actually, I could not image it and I forgot that they were inherited from parent process to child process.

            – Goktug
            Mar 4 '18 at 11:46





            You are right. Actually, I could not image it and I forgot that they were inherited from parent process to child process.

            – Goktug
            Mar 4 '18 at 11:46













            I wrote a code in which the child process try to read a file opened by its parent process previously. Actually, the operating system does not let the child process read the file. There is a while loop in both parent and child process to read the file. At first, parent process read some contents of the file. Then, child process is executed and child process's ID is printed. When the execution comes to the while loop which reads the file in child process, operating system continue to execute parent process. In other words, it never executes the while loop in child process.

            – Goktug
            Mar 5 '18 at 17:54







            I wrote a code in which the child process try to read a file opened by its parent process previously. Actually, the operating system does not let the child process read the file. There is a while loop in both parent and child process to read the file. At first, parent process read some contents of the file. Then, child process is executed and child process's ID is printed. When the execution comes to the while loop which reads the file in child process, operating system continue to execute parent process. In other words, it never executes the while loop in child process.

            – Goktug
            Mar 5 '18 at 17:54















            @Goktug Since file pointers are shared between parent and child, and if the parent had already reached end-of-file, then any attempt to read from the same file pointer in the child would return end-of-file immediately.

            – Kusalananda
            Mar 5 '18 at 17:56





            @Goktug Since file pointers are shared between parent and child, and if the parent had already reached end-of-file, then any attempt to read from the same file pointer in the child would return end-of-file immediately.

            – Kusalananda
            Mar 5 '18 at 17:56













            0














            And here is some example code that does just that.



            #include <err.h>
            #include <stdio.h>
            #include <unistd.h>

            char buf[8];

            int main(int argc, char *argv)
            {
            int ch, fd[2], rv;

            pipe(fd);

            switch (fork()) {
            case -1:
            err(1, "could not fork");
            case 0: // child
            rv = lseek(STDIN_FILENO, -7, SEEK_END);
            if (rv == -1) err(1, "could not seek");
            sleep(3);
            close(fd[1]);
            break;
            default: // parent
            close(fd[1]);
            read(fd[0], &ch, 1);
            read(STDIN_FILENO, buf, 7);
            printf("read '%s'n", buf);
            }
            return 0;
            }


            what is going on is that the parent blocks waiting for the child and meanwhile the child seeks to the end of standard input, minus seven, then closes the pipe(2) to the parent. This unblocks the parent, which reads from the shared descriptor from where the child moved the shared file pointer to.



            $ make sharedseek
            cc sharedseek.c -o sharedseek
            $ echo asdfasdfasdf123456 > x
            $ ./sharedseek < x
            read '123456
            '
            $


            This will not work if standard input is not seekable. Also the pipe (or some form of communication) is really necessary as otherwise the parent may run before the child.



            If the file descriptor was not shared then the parent would not read from where the child moved the pointer to.






            share|improve this answer






























              0














              And here is some example code that does just that.



              #include <err.h>
              #include <stdio.h>
              #include <unistd.h>

              char buf[8];

              int main(int argc, char *argv)
              {
              int ch, fd[2], rv;

              pipe(fd);

              switch (fork()) {
              case -1:
              err(1, "could not fork");
              case 0: // child
              rv = lseek(STDIN_FILENO, -7, SEEK_END);
              if (rv == -1) err(1, "could not seek");
              sleep(3);
              close(fd[1]);
              break;
              default: // parent
              close(fd[1]);
              read(fd[0], &ch, 1);
              read(STDIN_FILENO, buf, 7);
              printf("read '%s'n", buf);
              }
              return 0;
              }


              what is going on is that the parent blocks waiting for the child and meanwhile the child seeks to the end of standard input, minus seven, then closes the pipe(2) to the parent. This unblocks the parent, which reads from the shared descriptor from where the child moved the shared file pointer to.



              $ make sharedseek
              cc sharedseek.c -o sharedseek
              $ echo asdfasdfasdf123456 > x
              $ ./sharedseek < x
              read '123456
              '
              $


              This will not work if standard input is not seekable. Also the pipe (or some form of communication) is really necessary as otherwise the parent may run before the child.



              If the file descriptor was not shared then the parent would not read from where the child moved the pointer to.






              share|improve this answer




























                0












                0








                0







                And here is some example code that does just that.



                #include <err.h>
                #include <stdio.h>
                #include <unistd.h>

                char buf[8];

                int main(int argc, char *argv)
                {
                int ch, fd[2], rv;

                pipe(fd);

                switch (fork()) {
                case -1:
                err(1, "could not fork");
                case 0: // child
                rv = lseek(STDIN_FILENO, -7, SEEK_END);
                if (rv == -1) err(1, "could not seek");
                sleep(3);
                close(fd[1]);
                break;
                default: // parent
                close(fd[1]);
                read(fd[0], &ch, 1);
                read(STDIN_FILENO, buf, 7);
                printf("read '%s'n", buf);
                }
                return 0;
                }


                what is going on is that the parent blocks waiting for the child and meanwhile the child seeks to the end of standard input, minus seven, then closes the pipe(2) to the parent. This unblocks the parent, which reads from the shared descriptor from where the child moved the shared file pointer to.



                $ make sharedseek
                cc sharedseek.c -o sharedseek
                $ echo asdfasdfasdf123456 > x
                $ ./sharedseek < x
                read '123456
                '
                $


                This will not work if standard input is not seekable. Also the pipe (or some form of communication) is really necessary as otherwise the parent may run before the child.



                If the file descriptor was not shared then the parent would not read from where the child moved the pointer to.






                share|improve this answer















                And here is some example code that does just that.



                #include <err.h>
                #include <stdio.h>
                #include <unistd.h>

                char buf[8];

                int main(int argc, char *argv)
                {
                int ch, fd[2], rv;

                pipe(fd);

                switch (fork()) {
                case -1:
                err(1, "could not fork");
                case 0: // child
                rv = lseek(STDIN_FILENO, -7, SEEK_END);
                if (rv == -1) err(1, "could not seek");
                sleep(3);
                close(fd[1]);
                break;
                default: // parent
                close(fd[1]);
                read(fd[0], &ch, 1);
                read(STDIN_FILENO, buf, 7);
                printf("read '%s'n", buf);
                }
                return 0;
                }


                what is going on is that the parent blocks waiting for the child and meanwhile the child seeks to the end of standard input, minus seven, then closes the pipe(2) to the parent. This unblocks the parent, which reads from the shared descriptor from where the child moved the shared file pointer to.



                $ make sharedseek
                cc sharedseek.c -o sharedseek
                $ echo asdfasdfasdf123456 > x
                $ ./sharedseek < x
                read '123456
                '
                $


                This will not work if standard input is not seekable. Also the pipe (or some form of communication) is really necessary as otherwise the parent may run before the child.



                If the file descriptor was not shared then the parent would not read from where the child moved the pointer to.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 14 at 19:57

























                answered Mar 4 '18 at 15:29









                thrigthrig

                24.5k23056




                24.5k23056






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Unix & Linux Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f428043%2ffile-operations-and-processes%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to make a Squid Proxy server?

                    第一次世界大戦

                    Touch on Surface Book