Calling fork multiple times

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 เม.ย. 2020
  • Check out our Discord server: / discord

ความคิดเห็น • 162

  • @nathancordos9150
    @nathancordos9150 3 ปีที่แล้ว +53

    The sound of that keyboard makes life better.

  • @kornelkonyari2719
    @kornelkonyari2719 ปีที่แล้ว +37

    If anyone wondering, here is an illustration of the relationships between the processes, and some explanation of the while() loop in the end, which was the hardest part for me.
    parent
    / \
    (1)child/ x (2)secondChild/ z
    /
    (2)grandChild/ y
    (1): created by 1st fork
    (2): created by 2nd fork
    Explanation of the while() at the end:
    The conditions set up in a way to make sure that a process can only break out of the loop if it has no more children alive. It is necessary because of the reasons explained in the video. The first process that will successfully break out of it will be either y or z, as they have no children to wait for: so wait() will return -1, and errno will be set to ECHILD .
    Now the tricky part starts here, because lets say it was process z that just terminated: its parent process was also waiting for one of its children(z or x) to finish. So lets look at what is going on in the parent after z terminated.
    So after z finished running, the wait() call will return in the parent, and the loop will evaluate the return value, which wont be -1 in this case, because parent had a child (z) which just terminated. And this is why wait() is called inside a loop: in the case wait() returned in the parent, but it is not desired to continue execution in the parent, the parent process will get stuck at the wait() again instead of continuing. It will get inside the loop and print "Waited for child to finish", it will then loop back to the wait call, and since it has one more child (x) alive, it will wait for that child to change state.
    This cycle will keep repeating until there are no children to wait for in the parent process.
    The fact that the printf() inside the while loop printed 3 times means that there were 3 cases in total when wait() didn't produce an error, meaning 3 times when a process had a child process that terminated. One printf() comes from the parent when z terminated, one comes from x when y terminated, and the 3rd one comes from parent again when x terminated. So each time the wait() function didn't produce an error, the while loop kept calling it again and forced it to produce one, which I personally find interesting.
    After z terminated the parent produced the first printf() from inside the loop. Then the only process that can do anything is y, which has no other children, so the wait() inside y will return with -1 and y will terminate as well. This then will be detected by the wait() inside x which was waiting for y to exit, but in this case wait() returns the pid of y, meaning that x will go inside the while loop and print the second "Waited for child to finish" msg, which serves no real purpose at this time, as there are no other children that x is waiting for. So after the printf(), x will have to loop back and make a call to wait() again until all of its children terminated. If x, or any of the processes had more than one child, the loop would make sure that all of them are properly terminated.
    Suggestion: instead of calling wait() at the end of the function and printing the same stuff from all of the children, call it at the start, right after you forked.
    You already have an if else tree to identify all the processes, so if you printf() AFTER you waited can use it to visualize who waited for who and see if the code really worked as expected or not.
    The parent should print last, and y should print before x.
    int main()
    {
    int id1 = fork();
    int id2 = fork();
    while (wait(NULL) != -1 || errno != ECHILD)
    {
    ;
    }
    if (id1 == 0)
    {
    if (id2 == 0)
    {
    printf("grandchild
    ");
    }
    else
    {
    printf("1st child of parent
    ");
    }
    }
    else
    {
    if (id2 == 0)
    {
    printf("2nd child of parent
    ");
    }
    else
    {
    printf("parent
    ");
    }
    }
    return (0);
    }
    So in this case the possible outputs would be:
    2nd child
    grandchild
    1st child
    parent
    or:
    grandchild
    1st child
    2nd child
    parent

    • @CodeVault
      @CodeVault  ปีที่แล้ว +11

      Very nice explanation!
      One thing to note here is that waiting at the start makes all the processes sequential so you no longer have the benefits of executing multiple processes at the same time

    • @kornelkonyari2719
      @kornelkonyari2719 ปีที่แล้ว

      True. I studied the code to understand how wait in that while loop works, as that was the mistery part for me. For that purpose it was very helpful to see who is first who is last. But I guess the video was more about fork and processes in general.

    • @jamshidbek2000
      @jamshidbek2000 ปีที่แล้ว

      Thank you for the content! But I have a question.
      How can we make so that grandchild finishes first? Then any of the children one after another. And last parent finishes?
      I struggle with making the grandchild to finish first

    • @kornelkonyari2719
      @kornelkonyari2719 ปีที่แล้ว +1

      @@jamshidbek2000 It's already kinda happening, because the processes that dont have a child process of their own are always finishing first. So it's either the grandchild that finishes first(grandchild, 2nd child, 1st child, parent), or the second child(2nd child, grandchild, 1st child, parent). So there are two cases, and its random which one goes first.
      If you want to absolutely make sure that its always the grandchild that terminates first, well then you probably already screwed up. Because in this case, there was only 2 forks, so only 4 processes. But if there was another one, then you would have to manage 8 processes, then select the members of the youngest generation, terminate those, move on to the older generation and so on. What you want to do instead is probably always fork from the original parent process, and then this one parent process can easily manage all of its childeren directly.

  • @karlrombauts4909
    @karlrombauts4909 2 ปีที่แล้ว +28

    Thank you so much for making this series! This is by far the best-explained content on managing processes in C. It has helped me tremendously in my operating systems class!

  • @denied_9
    @denied_9 4 ปีที่แล้ว +16

    Such an underrated channel, well explained and helps alot!

  • @moonbaboon5493
    @moonbaboon5493 2 ปีที่แล้ว

    This channel is something else. Thanks man!

  • @DerNamenLose1222
    @DerNamenLose1222 4 ปีที่แล้ว +8

    you explain it so well, much appreciated

  • @dkkkkkkk
    @dkkkkkkk 3 ปีที่แล้ว +1

    this video saves my homework today! Very much appreciate it!! This channel is so helpful!

  • @TheLIMAK8
    @TheLIMAK8 ปีที่แล้ว

    Best Guide Ever ! Everything is so clear ! Thank you !

  • @bama2619
    @bama2619 3 ปีที่แล้ว

    i have got lost I need to rewatch. Thank you for the job!

  • @narendraparmar1631
    @narendraparmar1631 3 ปีที่แล้ว

    Good one bro you make the fork more clear now
    Keep going

  • @davidyenni3455
    @davidyenni3455 3 หลายเดือนก่อน

    You have made very, very good videos! Thank you so much! God bless, David

  • @mohamedmoumni7733
    @mohamedmoumni7733 2 ปีที่แล้ว

    Thank You for This Wonderful Playlist

  • @gurumeharrachaputi6026
    @gurumeharrachaputi6026 3 ปีที่แล้ว +1

    Perfect delivery...👏👏👏thank you very much...

  • @MT-fd6vu
    @MT-fd6vu 3 ปีที่แล้ว +4

    What a hidden treasure from youtube

  • @canaldoobmarcos4141
    @canaldoobmarcos4141 ปีที่แล้ว

    Very well explained. Thanks a lot!

  • @dismist7529
    @dismist7529 3 ปีที่แล้ว

    Thank u so much! Great explanation

  • @opensourcemundo3415
    @opensourcemundo3415 3 ปีที่แล้ว

    Awesome work, man! Keep it up!

  • @kolman9229
    @kolman9229 2 ปีที่แล้ว

    Thanks! You helped me with my home assignment!👍

  • @amanvarshney51217
    @amanvarshney51217 2 ปีที่แล้ว

    Thank you sir It really helped me a lot

  • @valentinaesteban9699
    @valentinaesteban9699 4 ปีที่แล้ว

    really good videos ,thank you sooooo much!!!!!

  • @guillaumeduchesne4602
    @guillaumeduchesne4602 ปีที่แล้ว

    thank u saved me so much time

  • @user-yz7ts2fq9m
    @user-yz7ts2fq9m 3 ปีที่แล้ว +5

    Here before this channel get famous!

  • @oblomov4058
    @oblomov4058 3 หลายเดือนก่อน

    you are great man you are a king

  • @jorgepulidolozano5277
    @jorgepulidolozano5277 2 ปีที่แล้ว +1

    Thank codeVault for the explanation it helped me to understand better how fork works. I am facing a trouble for one class asigment that I would ask you how to proceed.
    I have a function with 2 integers entries, one for height and other for width. Your video has shown me how I can have clones of the same process and have only one clone but I can't figure out how to integrate those variables into a loop.
    The case is that the tree will go down x=height levels starting from the initial process, and the first child of each level will have y=width children, except in the last level where there will be (witdh -1) children. I know that there should be 2 for loop the external with height and the internal with width. All children exit the two loops and terminate after being created, except for the last one, i.e. when j == width - 1, which continues with another repetition of the outer loop.
    So if height=4 and width=3 the tree should have the following patter:
    A -----B
    |---C
    |---D ---- E
    |-- F
    |-- G -------H
    |-- I
    |-- J -----K
    |-- M
    Thank in advance.

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว +12

      Sooo... I think it's something like this that you want:
      int width = 3;
      int height = 4;
      int i, j;
      printf("Root: %d
      ", getpid());
      for (i = 0; i < height; i++) {
      for (j = 0; j < width; j++) {
      if (j == width - 1 && i == height - 1) {
      break;
      }
      if (fork() == 0) {
      break;
      }
      }
      if (j != width - 1) {
      break;
      }
      }
      printf("Process %d with parent %d
      ", getpid(), getppid());
      while (wait(NULL) != -1 || errno != ECHILD) {} // Just for waiting for all the child processes to finish
      It looks a bit complex but basically it's ALL about controlling when to stop loops. The inner loop executes basically only for the parent processes (of the child processes created in that loop), this is what that break is for:
      if (fork() == 0) {
      break;
      }
      Next, we look at the LAST value of j in the outer loop. To determine which process continues the outer loop, we look at the value of j and we can notice that for
      A, j = width
      B, j = 0
      C, j = 1
      D, j = 2
      Since we want D to continue the loop, and j = 2 is j = width -1 in this case, we want ALL the other processes to break if their j value is width - 1, this is what that if is for:
      if (j != width - 1) {
      break;
      }
      And lastly, to make sure we have width * height number of total processes we use this break for the absolute last process so that it doesn't create an extra process:
      if (j == width - 1 && i == height - 1) {
      break;
      }
      And that should be everything. You might need an array for storing all the pids to figure what you need to do in each process

  • @devaharshabt5414
    @devaharshabt5414 3 ปีที่แล้ว

    Crystal clear explanation!

  • @lunadobbysnape461
    @lunadobbysnape461 ปีที่แล้ว

    ❤Thank u so much!It really helps me! Pleae make more❤❤❤

  • @nabeentiwaree8204
    @nabeentiwaree8204 2 ปีที่แล้ว

    Found a channel to master C.
    Thank you for your efforts : )

  • @reallydarkmatter
    @reallydarkmatter 3 ปีที่แล้ว

    This channel is Wonderful

  • @jasmineqj6570
    @jasmineqj6570 2 ปีที่แล้ว

    You saved me thank you so much!

  • @SkandanKA
    @SkandanKA 3 ปีที่แล้ว

    Thank you so much for all the videos..
    Please keep doing more and more ♥️😊..

  • @puzzlelovers529
    @puzzlelovers529 3 ปีที่แล้ว +8

    Okay, so we are not gonna talk about how handsome the presenter is.

  • @simonapopa9397
    @simonapopa9397 ปีที่แล้ว

    love it!

  • @vitcovschiantonio4416
    @vitcovschiantonio4416 3 ปีที่แล้ว

    Foarte tare, multam mult!

  • @shaantanukulkarni5668
    @shaantanukulkarni5668 2 ปีที่แล้ว

    Nice content 👍

  • @emirhandemir3872
    @emirhandemir3872 2 หลายเดือนก่อน

    Things got lot more complicated but I'm still able to keep up with the help of GPT. I love you OpenAI!

    • @CodeVault
      @CodeVault  2 หลายเดือนก่อน +1

      Just be careful, GPT, a lot of the time, provides wrong information

  • @xinking2644
    @xinking2644 ปีที่แล้ว

    excellent video!!!thank you very much!

  • @Ameerdala
    @Ameerdala 2 ปีที่แล้ว

    wow multiple fork() was a nightmare to me! this guy made it very easy!

  • @lakshanjayaweera6232
    @lakshanjayaweera6232 3 ปีที่แล้ว

    great program. Keep it up.

  • @navidnouri151
    @navidnouri151 2 ปีที่แล้ว +1

    veryyyyyyyyyyyy good! Thank you so muchhhhhhhh!

  • @abdelazizelhayyany6087
    @abdelazizelhayyany6087 2 ปีที่แล้ว +1

    thank you so much for your help, I have a question at12:41 if we wait for every child process does the out put should be from process y or/and z then x and then the parent's turn or just like it at 12:41

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว +1

      Well, depends where you wait for the processes. Since we first print the message and then we wait for the child processes the order is basically random. An important thing is that the order of printing for the child processes will always be random (at least in this example, you could make them more predictable but it's a bit complicated)

  • @henryhung4442
    @henryhung4442 ปีที่แล้ว

    Thank you!

  • @danieleliasvarghese459
    @danieleliasvarghese459 3 ปีที่แล้ว +2

    Can you explain the scenario if we have loops in these 4 processes and the processes are exchanging the different values in the loops.

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +2

      Alright, I'll make a video on this topic

  • @howard_yin
    @howard_yin ปีที่แล้ว

    thank you very much.
    I have one more question: which of these processes run first?

    • @CodeVault
      @CodeVault  ปีที่แล้ว +1

      Usually the first one that is created runs first but that is not guaranteed so you shouldn't make that assumption when developing your code

  • @jamshidbek2000
    @jamshidbek2000 ปีที่แล้ว

    Thank you for the content! But I have a question.
    How can we make so that grandchild finishes first? Then any of the children one after another. And last parent finishes?
    I struggle with making the grandchild to finish first

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      That while loop at the end with the wait() calls should do what you want

  • @georgioziozas9031
    @georgioziozas9031 3 ปีที่แล้ว

    great great visulization

  • @PixelPerfectBlade
    @PixelPerfectBlade 2 ปีที่แล้ว +1

    My goal is to create n process, so I had a for loop going from 0 to log(n)
    But then, what if n is not a power of 2? How can I chose the correct processes to fork in?

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว +5

      You can create any number of processes you want. For example here is a for loop that creates 5 processes:
      int i;
      for (i = 0; i < 5; i++) {
      int pid = fork();
      if (pid == 0) {
      break;
      }
      }
      // here you have 5 processes + the main process executing

    • @PixelPerfectBlade
      @PixelPerfectBlade 2 ปีที่แล้ว

      @@CodeVault I managed to get it yesterday! Still Thanks a lot for your help!

  • @manasachowdary180
    @manasachowdary180 3 ปีที่แล้ว

    Could you please tell me the order of process when we print id1 and id2 simultaneously

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว

      What do you mean by that? The order of execution of processes (or threads for that matter) is undetermined.

  • @aakashshah4381
    @aakashshah4381 3 ปีที่แล้ว +1

    very well explained. I am just curious, what do you exactly do professionally?

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +4

      I am a web developer

    • @iorch82
      @iorch82 3 ปีที่แล้ว

      @@CodeVault Very interesting. Do you miss dealing with all this low level concepts in your job?

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +11

      @@iorch82 Sometimes. With C, while the performance was really high up, the code quality wasn't that great due to its imperative nature... It always felt like I was creating either incredibly large functions or a LOT of small functions, and you didn't have much in terms of flexibility. In web development, I like that you can generalize a lot of things, have a lot of ways to increase the code quality and can easily iterate through designs, albeit at a performance penalty.
      Overall, I like both. I like tinkering with low level features of an operating system but I also like working at a high level implementing apps for multiple platforms at once.

  • @fadieid5638
    @fadieid5638 ปีที่แล้ว

    Just a quick question, I know that the processes running "shares the same memory space", but does it mean that both processes are executing the same program in RAM? Or is it that the child process executes a copy of the parent process? Was if there was a global variable which was changed it the block that runs by the child process and the child process changes that variable, does the parent process perceive that change also? What about the pointers or reference variables such as array?

    • @CodeVault
      @CodeVault  ปีที่แล้ว +1

      In the RAM itself, the processes use different parts of it. So the answer is no, they wouldn't see each other's changes of global variables

    • @fadieid5638
      @fadieid5638 ปีที่แล้ว

      @@CodeVault thank you

  • @Rita-og7cy
    @Rita-og7cy 3 ปีที่แล้ว

    he's great

  • @pulgamecanica
    @pulgamecanica 2 ปีที่แล้ว

    We can use the MACROS defined in the man page (man 2 wait) **WIFEXITED** for example right instead of using the while loop?
    Then u can tell the main process to wait fot a determined process to finish...

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว +1

      Yes. That is correct

  • @naitside3410
    @naitside3410 2 ปีที่แล้ว

    Я смотрю тебя через голосовой переводчик встроенный в яндекс браузер, первые 3 видео в плейлисте я очень хорошо понял, а видео 4 и 5 как то в переводе трудно воспринимать) попробую пересмотреть может пойму

  • @Sammito1111
    @Sammito1111 3 ปีที่แล้ว

    How come in this example we don't put the wait() before each process output? Wouldn't that be how we control our output order? I don't see why it was placed after the processes could have already executed the print statements. Thanks for the great video!

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +3

      The wait() call waits for a change of state (usually process termination) from a child process and FREES the resources associated with that child process. Now, in the video we didn't care about order of execution but, so that we don't cause any resource leaks, we called wait.
      Definitely you can also do what you're asking there. Although it is a bit more complex since 2 of the processes don't have a child process (so calling wait() in them wouldn't do anything) and you'd need to probably wait() in the parent process before forking the process z.
      So, whether you want control of the order of execution or not, you always should call wait() if you create child processes using fork().

    • @suhass5979
      @suhass5979 ปีที่แล้ว

      @@CodeVault u r a life saver TQ bro

  • @VishalSharma-ys9wt
    @VishalSharma-ys9wt ปีที่แล้ว

    What's the purpose of errno check in the condition on line 24? Why isn't wait(NULL) itself sufficient?

    • @CodeVault
      @CodeVault  ปีที่แล้ว +2

      wait(NULL) would wait for only 1 child process to finish. It will be called on all the processes so you'd think that's enough.
      But, let's say that in the program we have, the main process calls wait(NULL) first and foremost and waits successfully for one of his child processes to finish execution. Then, since we're only waiting for one process, the main process exits. All this while the other child process we had running is still executing but now, since its parent process finished its execution, it no longer has a valid parent process and is considered a zombie process until it exits.
      That while loop is to prevent a zombie process from being created

  • @BlindTV.official
    @BlindTV.official ปีที่แล้ว +1

    hi codevalt your explanation is very nice and i see you checked every comment but i have one doubt...........???????????why id 1 of parent process is equal to id 1 of child 2 means child z?

    • @CodeVault
      @CodeVault  11 หลายเดือนก่อน

      The value of id1 was simply copied over to the child process. When calling fork() a process with exactly the same variables (and values) is created

  • @tornado-zex47
    @tornado-zex47 ปีที่แล้ว +1

    what's id2 exactly is it the second proccess or same proccess changed

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      id2 is just a variable that can be found in all of the processes we're creating. It has different values based on which process we are on

  • @paschalokafor9043
    @paschalokafor9043 ปีที่แล้ว

    You are so awesome bro.
    But please arent you suppose to use a logical AND in you while loop to check if wait returns -1 and errno is equals to ECHILD

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      Not really. A better way to understand the condition is to invert it:
      while (!(wait(NULL) == -1 && errno == ECHILD)) { ... }
      We're looping until we find an error (wait(NULL) return -1) AND the error is ECHILD (meaning it has no child processes to wait for anymore).

  • @One_piece1089
    @One_piece1089 8 หลายเดือนก่อน

    u r amazing😍

  • @uddipangoswami8427
    @uddipangoswami8427 2 ปีที่แล้ว

    How to create two child processes of a single parent process and display 0-10 in 1st child and 11-20 in second child

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว +1

      Something like this:
      int i;
      for (i = 0; i < 2; i++) { // two child processes
      if (fork() == 0) {
      // only child process needs to do something
      for (int j = 11 * i; j < 11 * (i + 1); j++) // if i = 0 then it prints from 0 to 10, if i = 1 then it prints from 11 - 20
      printf("%d, ", j);
      break; // We don't want the child process to continue executing the for loop
      }
      }

    • @uddipangoswami8427
      @uddipangoswami8427 2 ปีที่แล้ว

      @@CodeVault thank you

  • @ahmadqureshi4017
    @ahmadqureshi4017 3 ปีที่แล้ว

    How can you guarantee that there will always be 3 print calls of "waited for child process".
    What if the process Z (which is the leaf process created by parent) gets executed first of all without waiting for any child (as it doesn't have any), The parent process will then be waiting for only one process which is X and will print "waited for child process" only once and process X might wait for its created child Y and prints "waited ..." . In this execution manner i think there will be only 2 calls to that print statement.
    Not sure if i am correct, please clear up the confusion.
    Thanks.

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว

      That's not quite right. Even if a child process finishes its execution before the parent process gets to a "wait" call, you still get the same behaviour and calling wait later on still returns information about that child that finished its execution.

  • @sakkamouid3343
    @sakkamouid3343 ปีที่แล้ว

    In the explanation you drew in 5:04 : isn't the process with id z supposed to have only one id because it is only a child? same for the process with id y .

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      Yes, but the id1 is simply copied over from the main process (it doesn't mean that it has a child process with the process id being the value of id1). Same for the process with id y but here we copied the value 0 of id1 from our parent process x

  • @szabobence7327
    @szabobence7327 หลายเดือนก่อน

    Hey, CodeVault!
    First of all, you are a real hero! But you already know that from the others.
    I have a question for you - I'm in the hope you might answer me.
    I wrote a similar code based on your videos to output the ID's of the processes. Here is the output:
    I am a parent
    ---(0)PARENT---
    Currend ID: 18327, parent ID: 454
    I am a child of a parent
    ---(1)CHILD---
    Currend ID: 18328, parent ID: 18327
    I am a child of a parent
    ---(2)CHILD---
    Currend ID: 18329, parent ID: 452
    I am a child of a child
    ---(1)GRANDCHILD---
    Currend ID: 18330, parent ID: 18328
    What I am curious about is that how can be that the second child of the parent (---(2)CHILD---) has a different parent ID? Shouldn't it be same as the first child's parent ID?
    Thanks again for your work!

    • @szabobence7327
      @szabobence7327 หลายเดือนก่อน

      After a few run, I got even more times the different parent ID of a child process. How come it doesnt show the parent ID?

    • @CodeVault
      @CodeVault  หลายเดือนก่อน +1

      I have a feeling you are not waiting for all child processes to stop executing and that the OS is catching that and assigning a different process. Or it might be that the code is wrong in some way. Can you send it please so I can check?

    • @szabobence7327
      @szabobence7327 29 วันที่ผ่านมา

      @@CodeVault here you go:
      int main()
      {
      int id = fork();
      if (id == 0){
      sleep(0.5);
      printf("---- FIRST LINE ----
      ");
      printf("Hello from the id: %d
      ", id);
      }
      else {
      printf("---- FIRST LINE ----
      ");
      printf("Hello from the id: %d
      ", id);
      }
      if (id == 0){
      printf("Hello from the child process
      ");
      }
      else
      printf("Hello from the main process
      ");
      printf("
      ");
      printf("---- SECOND LINE ----
      ");
      id = fork();
      if (id == 0){
      printf("This is a child process, it won't fork itself again. id = %d
      ", id);
      }
      else {
      fork();
      printf("This is inside the for loop, iteration
      ");
      }
      return 0;
      }

  • @Abrar2150
    @Abrar2150 2 ปีที่แล้ว

    What are the solution where you get in the code
    If fork() fork
    Fork()
    I would like some exemple
    Thanks

  • @truongg4734
    @truongg4734 4 หลายเดือนก่อน

    niceeeeeeeeeeeee

  • @deepakkanseri8937
    @deepakkanseri8937 3 ปีที่แล้ว +1

    at 11:30 , shouldn't there be && instead of || ?
    correct me if I'm wrong

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +2

      No, the OR there is correct although that condition is a bit confusing. Basically wait(NULL) can fail (aka return -1) for multiple reasons. One of them being ECHILD (aka there "were no processes to wait for"). But if wait(NULL) fails with a different error, I want the loop to continue.
      Let's break it down:
      1) If there are no children to be waiting for this condition would evaluate as follows:
      wait(NULL) != -1 || errno != ECHILD
      -1 != -1 || ECHILD != ECHILD
      false || false
      false => therefore the loop stops
      2) If there are children to be waiting for but wait(NULL) fails for other reasons it would evaluate as follows:
      wait(NULL) != -1 || errno != ECHILD
      -1 != -1 || EINVAL != ECHILD
      false || true
      true => therefore the loop continues because there might be more child processes
      Actually, here's a bit of a homework for you, if you don't mind. Try to make that condition more readable

    • @deepakkanseri8937
      @deepakkanseri8937 3 ปีที่แล้ว

      @@CodeVaultyes, I got it. Thanks
      I'm onto that homework now.
      By the way, keep up this amazing work. This has been really helpful.

  • @asifsaad5827
    @asifsaad5827 ปีที่แล้ว

    how did you include all some of the headers files?
    some of them are showing for me!

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      Are you having issues with including files into your project?

    • @asifsaad5827
      @asifsaad5827 ปีที่แล้ว

      @@CodeVault yes, i am running from vscode and while i include some of the headers into my C program file, and then start to compile, the notification says to correct the includepath and the headers file is not found (i am running the program on Ubuntu)

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      Odd... Which header files are you including?

    • @asifsaad5827
      @asifsaad5827 ปีที่แล้ว

      @@CodeVault sys/wait.h , linux/init.h and some other headers which need to be installed by "sudo apt install linux-headers-$(uname -r)"

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      If you compile your code through the command line, does that work?

  • @arvindersingh9863
    @arvindersingh9863 4 ปีที่แล้ว

    At 4:50 , how you named the processes x,y and z?

    • @CodeVault
      @CodeVault  4 ปีที่แล้ว +3

      Because of how the code worked:
      int id1 = fork();
      int id2 = fork();
      The first fork creates one new process. Its process id is stored in id1 (which I gave the value x).
      In that same child process, we call fork, create a new process and store its id in id2 (which I gave the value y)
      And lastly, the parent process also calls fork a second time and stores its id in id2 (which I gave the value z).
      So, the x is from the value of id1 in the parent process.
      The y, z are the values of id2 in their parent process.

    • @youcefsb4708
      @youcefsb4708 4 ปีที่แล้ว +1

      "Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process."
      The return value of fork() shouldn't be named id in the program, that's the return value of getpid().

    • @CodeVault
      @CodeVault  4 ปีที่แล้ว +1

      I see your point. But then what would a better name for it be?

    • @youcefsb4708
      @youcefsb4708 4 ปีที่แล้ว

      @@CodeVault Actually I am just learning from you, maybe hasChild or cid (child id) or pchild (process child), that would be more accurate.
      BTW tons of thanks for this playlist.

    • @CodeVault
      @CodeVault  4 ปีที่แล้ว +1

      @@youcefsb4708 Hmm, you're right, child_id (or cid) would be more suited to this. I'll consider using it in the future videos.
      Any feedback is much appreciated so thank you for that!

  • @AhmedElamoryDev
    @AhmedElamoryDev 3 ปีที่แล้ว

  • @MrNobody-rx3ny
    @MrNobody-rx3ny 3 ปีที่แล้ว

    int id1 = fork();
    if(id1 == 0){
    exec();
    }
    int id2 = fork();
    if(id2 == 0){
    exec();
    }
    // main process
    wait(NULL);
    wait(NULL);
    return 0;
    Ensured that exec receives valid input.
    As main process had 2 children I added 2 waits, but actually only one wait is required and gives desired output.
    For 2 waits it gave output but it's stucked which implies it's waiting.
    Can you please explain why only one wait is required and not two.

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +1

      Hmm... 2 waits are required here. Double check that the exec is actually doing something, maybe you can send me the complete code snippet and I'll look into it

    • @MrNobody-rx3ny
      @MrNobody-rx3ny 3 ปีที่แล้ว

      @@CodeVault only one wait is needed since I was trying to implement pipe function of shell.
      All the processes that are created in same fork seems to be constituting one job and wait(NULL) will wait for that one job ( which consisted many execs).

  • @jijobuje
    @jijobuje 2 ปีที่แล้ว

    Shouldn't the while block be written right after the line 24?

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว +1

      That would only wait for processes to finish in the main process, but in our case we have some child processes that also have child processes of their own. So, instead, we just wait for any child process of any process in our process tree

  • @saralopes1965
    @saralopes1965 ปีที่แล้ว

    can i call that process as "grandpa" father and child?

    • @CodeVault
      @CodeVault  ปีที่แล้ว +1

      Yea

    • @saralopes1965
      @saralopes1965 ปีที่แล้ว

      @@CodeVault thank you for your amazing video , it really helped me understand it more!

  • @21argi
    @21argi 3 ปีที่แล้ว +1

    what if we want to create a process with 3 children for example?

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +4

      The easiest way is to check if you're on the parent process and only fork then. Something like this:
      int pid1 = fork();
      if (pid1 == 0) {
      // Child 1
      return 0;
      }
      // Parent
      int pid2 = fork();
      if (pid2 == 0) {
      // Child 2
      return 0;
      }
      int pid3 = fork();
      if (pid3 == 0) {
      // Child 3
      return 0;
      }

    • @21argi
      @21argi 3 ปีที่แล้ว +1

      and if we don’t know the exact number of processes?
      let’s say we need “n” child processes.

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +2

      Simply have a for loop that you break out of on each child. Something like this:
      for (int i = 0; i < n; i++) {
      pid_arr[i] = fork();
      if (pid_arr[i] == 0) {
      break;
      }
      }
      // here you'll have n processes executing + the parent process

  • @udithkumarv734
    @udithkumarv734 3 ปีที่แล้ว

    the red and blue really screwed up my eyes, but otherwise, great videos! Thanks a lot!

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +1

      I thought it would stand out more. I'll more mild colors next time

  • @anjalichaudhary2782
    @anjalichaudhary2782 3 ปีที่แล้ว

    what wait(NULL)!=-1 represents here

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +1

      Basically wait returns -1 if an error ocurres and I'm also checking if that error is ECHILD (which means that there are no other child processes to wait for). Here's the documentation for it (Just CTRL+F for "ECHILD" and "Return Value")
      man7.org/linux/man-pages/man2/wait.2.html

    • @anjalichaudhary2782
      @anjalichaudhary2782 3 ปีที่แล้ว

      Thank u so much,got it

  • @zyghom
    @zyghom 2 ปีที่แล้ว

    so while practicing this I have crashed my Mac completely - only power off helped - so nice ;-) All because of children ;)

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว +1

      Lol. My whole school's network went down at one point because of a simple for loop and a fork. Ever since then they limited the number of processes a user can create

    • @zyghom
      @zyghom 2 ปีที่แล้ว

      @@CodeVault I would expect MacOS to be clever enough but when it got 10k+ processes... no response from the system - ok, I did not wait long enough but I am surprised that Ctrl+C in terminal did not kill all of them... or maybe I did not give enough time

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว

      CTRL+C only terminates the current process. Doesn't necessarily terminate the rest. If you have, for example, the Finder process and you open a PDF with that Finder, when you close the Finder, it won't close the opened PDF as well even though the Finder process is the parent process of that PDF viewer (it's just an example, in practice this might be different)

    • @zyghom
      @zyghom 2 ปีที่แล้ว

      @@CodeVault that is why you are a guru and I am a student (btw 2 time older than the guru but who cares ;-) )

  • @kranthiraj667
    @kranthiraj667 3 ปีที่แล้ว

    Didnt understand why id1 of process z is x.

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว

      That's just because id1 was already set when we got to the fork that created process z. fork() COPIES all the values of all the variables from the parent to the child process. That's why id1 of z is actually x (even if process z is not the parent of x).

  • @swedsa6004
    @swedsa6004 ปีที่แล้ว +1

    4:40 Why is id1 not id1=0 ?

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      Because fork() was called after id1 was already asigned a value. So it just got copied to the second child process of the main process

  • @shivangisharma9778
    @shivangisharma9778 3 ปีที่แล้ว

    How do you think the order matters, as your run result is different than mine?
    Your run result:
    We are process x
    We are process y
    We are the parent process!
    We are process z
    Waited for a child to finish
    Waited for a child to finish
    Waited for a child to finish
    According to my thought process, in your case, the x and y spawn out of parent, so x, y, parent then z spawns from the parent and the children are executed.
    I get this as my run result:
    We are the parent process!
    We are process z
    We are process x
    Waited for a child to finish
    We are process y
    Waited for a child to finish
    Waited for a child to finish
    In my run result, it seems as though the parent created, then z and x created, the two children of the parent, then it is waiting for z to complete, y is created from x, y gets completed and then x gets completed.
    Am I thinking this correctly?

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +1

      All the processes are ran in parallel and the order is determined by the kernel. So even if you create the processes in a certain order the printf function might get executed in a different order simply because some of the processes had more time to execute than others.

    • @shivangisharma9778
      @shivangisharma9778 3 ปีที่แล้ว

      @@CodeVault So this means the z child got produced earlier as the x child forked to produce y ?

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +1

      It is possible. But it's also possible that they we're created in a different order but the printf calls were just scheduled this way

  • @spaghardo
    @spaghardo ปีที่แล้ว

    good explanation but next time please dont use red on blue, it hurt my eyes

    • @CodeVault
      @CodeVault  ปีที่แล้ว

      Ohh, my bad. I didn't realise it looked so bad

  • @archascents5157
    @archascents5157 3 ปีที่แล้ว

    This isn't very clear to me. at 3:42 you say "the memory is copied over to the new process and the new process has the same values as the parent processes when it forked" to explain why the bottom process, y, id = 0. okay, then why was the middle left process, x, id1 = 0 and not x if it's copied from the parent process. You say at 4:30 for the right box that its "[ id1 is ] just copied over from the parent process so its id is x." okay so why wasn't the other child's id1 = x? the explanation for these two middle level processes' inheritance seems contradictory. - you have one id1 that's copied from the parent to equal x and you have another child's id1 that wasn't copied and instead equals 0

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +2

      id1 and id2 are all copied in every instance of the child process. The difference is that, right after forking, they are assigned a different value depending on whether they are a child process or a parent process.
      int id1 = fork();
      fork() copies over the value of id1 (which currently just has some garbage value) then
      in the child process id1 gets assigned to 0 and
      in the parent process id1 gets assigned to the id of the child.
      They are indeed copied, it's just that we modify them in their respective processes. (Remember: memory is NOT shared between processes)

  • @liquidred257
    @liquidred257 9 หลายเดือนก่อน

    why don't you just do 2 wait() methods instead of what you do at 11:00?

    • @CodeVault
      @CodeVault  9 หลายเดือนก่อน

      Because some processes only have one child process

  • @hamids4550
    @hamids4550 3 ปีที่แล้ว

    you lost me with the diagram

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว

      What do you need explaining?

    • @hamids4550
      @hamids4550 3 ปีที่แล้ว

      @@CodeVault I got it when I rewatched it lol, it wasn't that difficult :D
      Thanks

  • @helpdesk9535
    @helpdesk9535 2 ปีที่แล้ว

    thanks for nothing. There are better people explaining this stuff. And you re wrong with some things

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว

      What was wrong in my explanation?

  • @poincareelcartografo5406
    @poincareelcartografo5406 ปีที่แล้ว

    If you wait(NULL) each time time you fork() (two times in this case), you will get the same result than using eerno != ECHILD