Skip to content

Commit 3f08a8b

Browse files
committed
add callback example
1 parent d2ee2f2 commit 3f08a8b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

example/system/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ ADD_EXAMPLE(process_2)
33
ADD_EXAMPLE(process_3)
44
ADD_EXAMPLE(process_4)
55
ADD_EXAMPLE(process_5)
6+
ADD_EXAMPLE(process_6)

example/system/example_process_6.f90

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
 (0)