|
| 1 | +! Process example 6: Demonstrate callback |
| 2 | +program example_process_6 |
| 3 | + use stdlib_system, only: process_type, process_ID, run, is_running, kill, elapsed, is_windows, sleep |
| 4 | + implicit none |
| 5 | + type(process_type) :: p |
| 6 | + integer, target :: nfiles |
| 7 | + |
| 8 | + ! Run process, attach callback function and some data |
| 9 | + if (is_windows()) then |
| 10 | + p = run("dir",want_stdout=.true.,callback=get_dir_nfiles) |
| 11 | + else |
| 12 | + p = run("ls -l",want_stdout=.true.,callback=get_dir_nfiles,payload=nfiles) |
| 13 | + endif |
| 14 | + |
| 15 | + ! On exit, the number of files should have been extracted by the callback function |
| 16 | + print *, "Current directory has ",nfiles," files" |
| 17 | + |
| 18 | + contains |
| 19 | + |
| 20 | + ! Custom callback function: retrieve number of files from ls output |
| 21 | + subroutine get_dir_nfiles(pid, exit_state, stdin, stdout, stderr, payload) |
| 22 | + integer(process_ID), intent(in) :: pid |
| 23 | + integer, intent(in) :: exit_state |
| 24 | + character(len=*), optional, intent(in) :: stdin, stdout, stderr |
| 25 | + class(*), optional, intent(inout) :: payload |
| 26 | + |
| 27 | + integer :: i |
| 28 | + |
| 29 | + if (present(payload)) then |
| 30 | + |
| 31 | + select type (nfiles => payload) |
| 32 | + type is (integer) |
| 33 | + if (present(stdout)) then |
| 34 | + nfiles = count([ (stdout(i:i) == char(10), i=1,len(stdout)) ]) |
| 35 | + else |
| 36 | + nfiles = -1 |
| 37 | + endif |
| 38 | + class default |
| 39 | + error stop 'Wrong payload passed to the process' |
| 40 | + end select |
| 41 | + |
| 42 | + end if |
| 43 | + end subroutine get_dir_nfiles |
| 44 | + |
| 45 | +end program example_process_6 |
0 commit comments