Exiting a Bash script when a sudo child quitsUsing nice on bash (or other) subshell?Install script - sudo...

Would a spacecraft carry arc welding supplies?

Is it really better for the environment if I take the stairs as opposed to a lift?

What is the etymology of とある?

Is the phrase “You are requested” polite or rude?

Rules on "Pets on shoulder"

Rawrdon Mamsay pays a visit

What actually is "unallocated space"?

What would a chair for a Human with a Tail look like?

A question about the Tannaka-Krein reconstruction of finite groups

In the old name Dreadnought, is nought an adverb or a noun?

Can elves trance in armor without any downsides?

In this day and age should the definition / categorisation of erotica be revised?

Meaning of “Bulldog drooled courses through his jowls”

When is "了" pronounced "le" and when is it pronounced "liao"?

Who inspired the character Geordi La Forge?

Why do military jets sometimes have elevators in a depressed position when parked?

Should I respond to a sabotage accusation e-mail at work?

Matrix class in C#

Why is 10.1.255.255 an invalid broadcast address?

Why were germanium diodes so fast and germanium transistors so slow?

Why can a T* be passed in register, but a unique_ptr<T> cannot?

How can a stock trade for a fraction of a cent?

How can I seal 8 inch round holes in my siding?

Is it okay to request a vegetarian only microwave at work ? If, yes, what's the proper way to do it?



Exiting a Bash script when a sudo child quits


Using nice on bash (or other) subshell?Install script - sudo authorisation compatibility?How to kill this process in bashKeep exit codes when trapping SIGINT and similar?Issue with bash script running from php as rootCan't run 'kill — -$$' in my shell script when I sudo itBASH loops, counters, child processes; counter not workingBash: when is a PID exactly freed up?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}








2

















I'm trying to launch a couple of sub-programs from a bash script and then wait on either of them to quit before quitting the other and exiting the script.




CMD1PID=
CMD2PID=

exit_trap () {
echo "exit trap: killing jobs..."
sudo kill $CMD1PID $CMD2PID
exit
}

set -bm
trap exit_trap EXIT INT TERM

sudo cmd1 --args &
CMD1PID=$?

sudo cmd2 --args &
CMD2PID=$?

wait $CMD1PID $CMD2PID



(For reference, this is GNU bash, version 4.2.37(1)-release (arm-unknown-linux-gnueabi) on Debian Weezy)



Unfortunately, this doesn't seem to work properly. I've tried several variants, such as:




  • using curly braces around the commands and explicitly killing the shell process afterwards, ie { cmd1 --args ; kill -USR1 $$ ; } & or similar, and then trapping on USR1

  • using kill 0 to kill the still-running commands at exit

  • trapping CHLD - this has the disadvantage that I can't sleep between the commands if I need to, which I might eventually need to do.


...but the issues I tend to run into are:




  • Killing one of the commands doesn't cause the parent Bash process to exit and/or kill the other command

  • Killing the parent Bash process doesn't cause both commands to be killed


I suspect that perhaps my requirement to use sudo is tripping me up, as other folks in other scripts seem to be having good luck with similar scripts. Is there a good way of doing what I'm trying to do in bash?










share|improve this question



































    2

















    I'm trying to launch a couple of sub-programs from a bash script and then wait on either of them to quit before quitting the other and exiting the script.




    CMD1PID=
    CMD2PID=

    exit_trap () {
    echo "exit trap: killing jobs..."
    sudo kill $CMD1PID $CMD2PID
    exit
    }

    set -bm
    trap exit_trap EXIT INT TERM

    sudo cmd1 --args &
    CMD1PID=$?

    sudo cmd2 --args &
    CMD2PID=$?

    wait $CMD1PID $CMD2PID



    (For reference, this is GNU bash, version 4.2.37(1)-release (arm-unknown-linux-gnueabi) on Debian Weezy)



    Unfortunately, this doesn't seem to work properly. I've tried several variants, such as:




    • using curly braces around the commands and explicitly killing the shell process afterwards, ie { cmd1 --args ; kill -USR1 $$ ; } & or similar, and then trapping on USR1

    • using kill 0 to kill the still-running commands at exit

    • trapping CHLD - this has the disadvantage that I can't sleep between the commands if I need to, which I might eventually need to do.


    ...but the issues I tend to run into are:




    • Killing one of the commands doesn't cause the parent Bash process to exit and/or kill the other command

    • Killing the parent Bash process doesn't cause both commands to be killed


    I suspect that perhaps my requirement to use sudo is tripping me up, as other folks in other scripts seem to be having good luck with similar scripts. Is there a good way of doing what I'm trying to do in bash?










    share|improve this question































      2












      2








      2








      I'm trying to launch a couple of sub-programs from a bash script and then wait on either of them to quit before quitting the other and exiting the script.




      CMD1PID=
      CMD2PID=

      exit_trap () {
      echo "exit trap: killing jobs..."
      sudo kill $CMD1PID $CMD2PID
      exit
      }

      set -bm
      trap exit_trap EXIT INT TERM

      sudo cmd1 --args &
      CMD1PID=$?

      sudo cmd2 --args &
      CMD2PID=$?

      wait $CMD1PID $CMD2PID



      (For reference, this is GNU bash, version 4.2.37(1)-release (arm-unknown-linux-gnueabi) on Debian Weezy)



      Unfortunately, this doesn't seem to work properly. I've tried several variants, such as:




      • using curly braces around the commands and explicitly killing the shell process afterwards, ie { cmd1 --args ; kill -USR1 $$ ; } & or similar, and then trapping on USR1

      • using kill 0 to kill the still-running commands at exit

      • trapping CHLD - this has the disadvantage that I can't sleep between the commands if I need to, which I might eventually need to do.


      ...but the issues I tend to run into are:




      • Killing one of the commands doesn't cause the parent Bash process to exit and/or kill the other command

      • Killing the parent Bash process doesn't cause both commands to be killed


      I suspect that perhaps my requirement to use sudo is tripping me up, as other folks in other scripts seem to be having good luck with similar scripts. Is there a good way of doing what I'm trying to do in bash?










      share|improve this question

















      I'm trying to launch a couple of sub-programs from a bash script and then wait on either of them to quit before quitting the other and exiting the script.




      CMD1PID=
      CMD2PID=

      exit_trap () {
      echo "exit trap: killing jobs..."
      sudo kill $CMD1PID $CMD2PID
      exit
      }

      set -bm
      trap exit_trap EXIT INT TERM

      sudo cmd1 --args &
      CMD1PID=$?

      sudo cmd2 --args &
      CMD2PID=$?

      wait $CMD1PID $CMD2PID



      (For reference, this is GNU bash, version 4.2.37(1)-release (arm-unknown-linux-gnueabi) on Debian Weezy)



      Unfortunately, this doesn't seem to work properly. I've tried several variants, such as:




      • using curly braces around the commands and explicitly killing the shell process afterwards, ie { cmd1 --args ; kill -USR1 $$ ; } & or similar, and then trapping on USR1

      • using kill 0 to kill the still-running commands at exit

      • trapping CHLD - this has the disadvantage that I can't sleep between the commands if I need to, which I might eventually need to do.


      ...but the issues I tend to run into are:




      • Killing one of the commands doesn't cause the parent Bash process to exit and/or kill the other command

      • Killing the parent Bash process doesn't cause both commands to be killed


      I suspect that perhaps my requirement to use sudo is tripping me up, as other folks in other scripts seem to be having good luck with similar scripts. Is there a good way of doing what I'm trying to do in bash?







      bash shell-script sudo






      share|improve this question
















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 31 '13 at 16:35







      jldeon

















      asked Oct 31 '13 at 16:22









      jldeonjldeon

      284 bronze badges




      284 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          2


















          You have two problems: You need to identify when any of the interesting children is done, and you need to kill all of them.



          The first means you cannot use the "wait" builtin, because that will wait for all children (or all of the listed ones, if any), not for any. Your USR1-based suggestion works well for that (and for EXIT).



          The second is much harder: Because you're using sudo, you don't actually have permission to send a signal to the processes; to send a signal to a process, either your userid must match, or you must be root.



          You could try to use filesystem- or filehandle-based signaling or something like that, but frankly, that's going to be much more understandable and readable and maintainable in some other scripting language (python, perl, whatever), and even then it's overly complicated. You're probably better off running the entire script under the target user.






          share|improve this answer


































            0


















            If I may suggest a UNIX-style “divide a complex task into smaller tasks”, I would start by solving the sudo issue, so that you’re left with a simpler “exiting a Bash script when a child quits” problem, where your shell is the direct parent of the children.



            #!/bin/sh

            exec sudo sh -c '
            exit_trap() {
            kill # pids
            }
            trap exit_trap SIGNALS
            # run children &
            wait # pids
            '


            Note that at this point, the script is basically a sudo-izing wrapper to the inner script in single quotes. I’m not sure it’s worth it, but maybe you have additional code to run before or after (in which case you want to remove exec) the sudo invocation, which makes the weirdness worthwhile.






            share|improve this answer









            New contributor



            raffaellod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.























              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/4.0/"u003ecc by-sa 4.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%2f98334%2fexiting-a-bash-script-when-a-sudo-child-quits%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









              2


















              You have two problems: You need to identify when any of the interesting children is done, and you need to kill all of them.



              The first means you cannot use the "wait" builtin, because that will wait for all children (or all of the listed ones, if any), not for any. Your USR1-based suggestion works well for that (and for EXIT).



              The second is much harder: Because you're using sudo, you don't actually have permission to send a signal to the processes; to send a signal to a process, either your userid must match, or you must be root.



              You could try to use filesystem- or filehandle-based signaling or something like that, but frankly, that's going to be much more understandable and readable and maintainable in some other scripting language (python, perl, whatever), and even then it's overly complicated. You're probably better off running the entire script under the target user.






              share|improve this answer































                2


















                You have two problems: You need to identify when any of the interesting children is done, and you need to kill all of them.



                The first means you cannot use the "wait" builtin, because that will wait for all children (or all of the listed ones, if any), not for any. Your USR1-based suggestion works well for that (and for EXIT).



                The second is much harder: Because you're using sudo, you don't actually have permission to send a signal to the processes; to send a signal to a process, either your userid must match, or you must be root.



                You could try to use filesystem- or filehandle-based signaling or something like that, but frankly, that's going to be much more understandable and readable and maintainable in some other scripting language (python, perl, whatever), and even then it's overly complicated. You're probably better off running the entire script under the target user.






                share|improve this answer





























                  2














                  2










                  2









                  You have two problems: You need to identify when any of the interesting children is done, and you need to kill all of them.



                  The first means you cannot use the "wait" builtin, because that will wait for all children (or all of the listed ones, if any), not for any. Your USR1-based suggestion works well for that (and for EXIT).



                  The second is much harder: Because you're using sudo, you don't actually have permission to send a signal to the processes; to send a signal to a process, either your userid must match, or you must be root.



                  You could try to use filesystem- or filehandle-based signaling or something like that, but frankly, that's going to be much more understandable and readable and maintainable in some other scripting language (python, perl, whatever), and even then it's overly complicated. You're probably better off running the entire script under the target user.






                  share|improve this answer














                  You have two problems: You need to identify when any of the interesting children is done, and you need to kill all of them.



                  The first means you cannot use the "wait" builtin, because that will wait for all children (or all of the listed ones, if any), not for any. Your USR1-based suggestion works well for that (and for EXIT).



                  The second is much harder: Because you're using sudo, you don't actually have permission to send a signal to the processes; to send a signal to a process, either your userid must match, or you must be root.



                  You could try to use filesystem- or filehandle-based signaling or something like that, but frankly, that's going to be much more understandable and readable and maintainable in some other scripting language (python, perl, whatever), and even then it's overly complicated. You're probably better off running the entire script under the target user.







                  share|improve this answer













                  share|improve this answer




                  share|improve this answer










                  answered Nov 12 '13 at 1:46









                  GabeGabe

                  1312 bronze badges




                  1312 bronze badges




























                      0


















                      If I may suggest a UNIX-style “divide a complex task into smaller tasks”, I would start by solving the sudo issue, so that you’re left with a simpler “exiting a Bash script when a child quits” problem, where your shell is the direct parent of the children.



                      #!/bin/sh

                      exec sudo sh -c '
                      exit_trap() {
                      kill # pids
                      }
                      trap exit_trap SIGNALS
                      # run children &
                      wait # pids
                      '


                      Note that at this point, the script is basically a sudo-izing wrapper to the inner script in single quotes. I’m not sure it’s worth it, but maybe you have additional code to run before or after (in which case you want to remove exec) the sudo invocation, which makes the weirdness worthwhile.






                      share|improve this answer









                      New contributor



                      raffaellod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.


























                        0


















                        If I may suggest a UNIX-style “divide a complex task into smaller tasks”, I would start by solving the sudo issue, so that you’re left with a simpler “exiting a Bash script when a child quits” problem, where your shell is the direct parent of the children.



                        #!/bin/sh

                        exec sudo sh -c '
                        exit_trap() {
                        kill # pids
                        }
                        trap exit_trap SIGNALS
                        # run children &
                        wait # pids
                        '


                        Note that at this point, the script is basically a sudo-izing wrapper to the inner script in single quotes. I’m not sure it’s worth it, but maybe you have additional code to run before or after (in which case you want to remove exec) the sudo invocation, which makes the weirdness worthwhile.






                        share|improve this answer









                        New contributor



                        raffaellod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.
























                          0














                          0










                          0









                          If I may suggest a UNIX-style “divide a complex task into smaller tasks”, I would start by solving the sudo issue, so that you’re left with a simpler “exiting a Bash script when a child quits” problem, where your shell is the direct parent of the children.



                          #!/bin/sh

                          exec sudo sh -c '
                          exit_trap() {
                          kill # pids
                          }
                          trap exit_trap SIGNALS
                          # run children &
                          wait # pids
                          '


                          Note that at this point, the script is basically a sudo-izing wrapper to the inner script in single quotes. I’m not sure it’s worth it, but maybe you have additional code to run before or after (in which case you want to remove exec) the sudo invocation, which makes the weirdness worthwhile.






                          share|improve this answer









                          New contributor



                          raffaellod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          If I may suggest a UNIX-style “divide a complex task into smaller tasks”, I would start by solving the sudo issue, so that you’re left with a simpler “exiting a Bash script when a child quits” problem, where your shell is the direct parent of the children.



                          #!/bin/sh

                          exec sudo sh -c '
                          exit_trap() {
                          kill # pids
                          }
                          trap exit_trap SIGNALS
                          # run children &
                          wait # pids
                          '


                          Note that at this point, the script is basically a sudo-izing wrapper to the inner script in single quotes. I’m not sure it’s worth it, but maybe you have additional code to run before or after (in which case you want to remove exec) the sudo invocation, which makes the weirdness worthwhile.







                          share|improve this answer









                          New contributor



                          raffaellod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.








                          share|improve this answer




                          share|improve this answer






                          New contributor



                          raffaellod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.








                          answered 12 mins ago









                          raffaellodraffaellod

                          1




                          1




                          New contributor



                          raffaellod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.




                          New contributor




                          raffaellod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.




































                              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%2f98334%2fexiting-a-bash-script-when-a-sudo-child-quits%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

                              Hudson River Historic District Contents Geography History The district today Aesthetics Cultural...

                              The number designs the writing. Feandra Aversely Definition: The act of ingrafting a sprig or shoot of one...

                              Ayherre Geografie Demografie Externe links Navigatiemenu43° 23′ NB, 1° 15′ WL43° 23′ NB, 1°...